﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using EMANIFEST.DataAccess.Models;
using EMANIFEST.Dtos;

namespace EMANIFEST.DataAccess
{
    public partial class BusinessDataAccess
    {
        public eManifestEntities eManifestModel;

        private enum enumDocumentUpdate
        {
            Crew = 1,
            CrewEffectDeclaration = 2,
            DangerousGood = 3,
            Passenger = 4,
            GeneralDeclaration = 5,
            GoodDeclaration = 6,
            ShipStoreDeclaration = 7,
            HouseBill = 8,
            MasterBill = 9,
        }

        #region Contructor

        /// <summary>
        /// New Contructor
        /// </summary>
        public BusinessDataAccess()
        {
            eManifestModel = new eManifestEntities();
        }

        /// <summary>
        /// New Contructor with connection string
        /// </summary>
        public BusinessDataAccess(string connectionString)
        {
            eManifestModel = new eManifestEntities(connectionString);
        }

        #endregion

        #region "Configuration"

        #region "State"

        /// <summary>
        /// Convert from model object to dto object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private StateDto ConvertStateModelToDto(State obj)
        {
            var ret = new StateDto
            {
                StateId = obj.StateId,
                Name = obj.Name,
                ShortName = obj.ShortName
            };

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        public StateDto GetStateById(Guid id)
        {
            StateDto ret = null;

            var get = (from o in eManifestModel.States
                       where o.StateId == id
                       select o).FirstOrDefault() as State;

            if (get != null)
            {
                ret = ConvertStateModelToDto(get);
            }

            return ret;
        }

        /// <summary>
        /// Get object by name
        /// </summary>
        /// <returns></returns>
        public StateDto GetStateByName(string name)
        {
            StateDto ret = null;

            var get = (from o in eManifestModel.States
                       where string.Compare(o.Name, name, true) == 0
                       select o).FirstOrDefault() as State;

            if (get != null)
            {
                ret = ConvertStateModelToDto(get);
            }

            return ret;
        }

        /// <summary>
        /// Get list States
        /// </summary>
        /// <returns></returns>
        public List<StateDto> GetListState()
        {
            var lstret = new List<StateDto>();

            var get = (from o in eManifestModel.States
                       select o);

            if (get != null)
            {
                foreach (var item in get)
                {
                    lstret.Add(ConvertStateModelToDto(item));
                }
            }

            return lstret;
        }

        /// <summary>
        /// Get list States
        /// </summary>
        /// <returns></returns>
        public Dictionary<Guid, StateDto> GetDicState()
        {
            var lstret = new Dictionary<Guid, StateDto>();

            var get = (from o in eManifestModel.States
                       select o);

            if (get != null)
            {
                foreach (var item in get)
                {
                    lstret.Add(item.StateId, ConvertStateModelToDto(item));
                }
            }

            return lstret;
        }
        #endregion

        #region "ShipType"

        /// <summary>
        /// Convert from model object to dto object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private ShipTypeDto ConvertShipTypeModelToDto(ShipType obj)
        {
            var ret = new ShipTypeDto
            {
                ShipTypeId = obj.ShipTypeId,
                Description = obj.Description
            };

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        public ShipTypeDto GetShipTypeById(Guid id)
        {
            ShipTypeDto ret = null;

            var get = (from o in eManifestModel.ShipTypes
                       where o.ShipTypeId == id
                       select o).FirstOrDefault() as ShipType;

            if (get != null)
            {
                ret = ConvertShipTypeModelToDto(get);
            }

            return ret;
        }

        /// <summary>
        /// Get list ShipTypes
        /// </summary>
        /// <returns></returns>
        public List<ShipTypeDto> GetListShipType()
        {
            var lstret = new List<ShipTypeDto>();

            var get = (from o in eManifestModel.ShipTypes
                       orderby o.ShipTypeId
                       select o);

            if (get != null)
            {
                foreach (var item in get)
                {
                    lstret.Add(ConvertShipTypeModelToDto(item));
                }
            }

            return lstret;
        }

        #endregion

        #region "DocumentStatus"

        /// <summary>
        /// Convert from model object to dto object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private DocumentStatusDto ConvertDocumentStatusModelToDto(DocumentStatu obj)
        {
            var ret = new DocumentStatusDto
            {
                StatusId = obj.StatusId,
                StatusName = obj.StatusName,
                Description = obj.Description
            };

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        public DocumentStatusDto GetDocumentStatusById(int id)
        {
            DocumentStatusDto ret = null;

            var get = (from o in eManifestModel.DocumentStatus
                       where o.StatusId == id
                       select o).FirstOrDefault() as DocumentStatu;

            if (get != null)
            {
                ret = ConvertDocumentStatusModelToDto(get);
            }

            return ret;
        }

        /// <summary>
        /// Get list DocumentStatuss
        /// </summary>
        /// <returns></returns>
        public List<DocumentStatusDto> GetListDocumentStatus()
        {
            var lstret = new List<DocumentStatusDto>();

            var get = (from o in eManifestModel.DocumentStatus
                       select o);

            if (get != null)
            {
                foreach (var item in get)
                {
                    lstret.Add(ConvertDocumentStatusModelToDto(item));
                }
            }

            return lstret;
        }

        #endregion

        #region "DocumentType"

        /// <summary>
        /// Convert from model object to dto object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private DocumentTypeDto ConvertDocumentTypeModelToDto(DocumentType obj)
        {
            var ret = new DocumentTypeDto
            {
                DocumentTypeId = obj.DocumentTypeId,
                Name = obj.Name,
                Description = obj.Description
            };

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        public DocumentTypeDto GetDocumentTypeById(int id)
        {
            DocumentTypeDto ret = null;

            var get = (from o in eManifestModel.DocumentTypes
                       where o.DocumentTypeId == id
                       select o).FirstOrDefault() as DocumentType;

            if (get != null)
            {
                ret = ConvertDocumentTypeModelToDto(get);
            }

            return ret;
        }

        /// <summary>
        /// Get list DocumentTypes
        /// </summary>
        /// <returns></returns>
        public List<DocumentTypeDto> GetListDocumentType()
        {
            var lstret = new List<DocumentTypeDto>();

            var get = (from o in eManifestModel.DocumentTypes
                       select o);

            if (get != null)
            {
                foreach (var item in get)
                {
                    lstret.Add(ConvertDocumentTypeModelToDto(item));
                }
            }

            return lstret;
        }
        /// <summary>
        /// Get list DocumentTypes
        /// </summary>
        /// <returns></returns>
        public Dictionary<int, DocumentTypeDto> GetDicDocumentType()
        {
            var lstret = new Dictionary<int, DocumentTypeDto>();

            var get = (from o in eManifestModel.DocumentTypes
                       select o);

            if (get != null)
            {
                foreach (var item in get)
                {
                    lstret.Add(item.DocumentTypeId, ConvertDocumentTypeModelToDto(item));
                }
            }

            return lstret;
        }
        #endregion

        #region "ItemCodeVN"

        /// <summary>
        /// Convert from model object to dto object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private ItemCodeVNDto ConvertItemCodeVNModelToDto(ItemCodeVN obj)
        {
            var ret = new ItemCodeVNDto
            {
                ItemId = obj.ItemId,
                Name = obj.Name,
                Description = obj.Description
            };

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        public ItemCodeVNDto GetItemCodeVNByItemId(string itemid)
        {
            ItemCodeVNDto ret = null;

            var get = (from o in eManifestModel.ItemCodeVNs
                       where string.Compare(o.ItemId, itemid, true) == 0
                       select o).FirstOrDefault() as ItemCodeVN;

            if (get != null)
            {
                ret = ConvertItemCodeVNModelToDto(get);
            }

            return ret;
        }

        /// <summary>
        /// Get list ItemCodeVNs
        /// </summary>
        /// <returns></returns>
        public List<ItemCodeVNDto> GetListItemCodeVN()
        {
            var lstret = new List<ItemCodeVNDto>();

            var get = (from o in eManifestModel.ItemCodeVNs
                       select o);

            if (get != null)
            {
                foreach (var item in get)
                {
                    lstret.Add(ConvertItemCodeVNModelToDto(item));
                }
            }

            return lstret;
        }

        #endregion

        #region "PassportType"

        /// <summary>
        /// Convert from model object to dto object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private PassportTypeDto ConvertPassportTypeModelToDto(PassportType obj)
        {
            var ret = new PassportTypeDto
            {
                PassportType = obj.PassportType1.Trim(),
                Description = obj.Description
            };

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        public PassportTypeDto GetPassportTypeById(string passportType)
        {
            PassportTypeDto ret = null;

            var get = (from o in eManifestModel.PassportTypes
                       where string.Compare(o.PassportType1, passportType, true) == 0
                       select o).FirstOrDefault() as PassportType;

            if (get != null)
            {
                ret = ConvertPassportTypeModelToDto(get);
            }

            return ret;
        }

        /// <summary>
        /// Get list PassportTypes
        /// </summary>
        /// <returns></returns>
        public List<PassportTypeDto> GetListPassportType()
        {
            var lstret = new List<PassportTypeDto>();

            var get = (from o in eManifestModel.PassportTypes
                       select o);

            if (get != null)
            {
                foreach (var item in get)
                {
                    lstret.Add(ConvertPassportTypeModelToDto(item));
                }
            }

            return lstret;
        }

        #endregion

        #region "Port"

        /// <summary>
        /// Convert from model object to dto object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private PortDto ConvertPortModelToDto(Port obj)
        {
            var ret = new PortDto
            {
                PortId = obj.PortId,
                StateId = obj.StateId,
                Name = string.IsNullOrEmpty(obj.Name) ? obj.Address : obj.Name,
                Address = obj.Address,
                PortCode = obj.PortCode.Trim(),
            };
            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        public PortDto GetPortById(Guid id)
        {
            PortDto ret = null;

            var get = eManifestModel.GetPortById(id).Single();

            if (get != null)
            {
                ret = ConvertPortModelToDto(get);
            }

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        private PortDto GetPortByName(string name)
        {
            PortDto ret = null;

            var get = (from o in eManifestModel.Ports
                       where string.Compare(o.Name, name, true) == 0
                       select o).FirstOrDefault() as Port;

            if (get != null)
            {
                ret = ConvertPortModelToDto(get);
            }

            return ret;
        }

        public List<PortDto> GetListPortByStateId(Guid stateId)
        {
            var lstret = new List<PortDto>();

            var get = (from o in eManifestModel.Ports
                       where o.StateId == stateId
                       select o);

            if (get != null)
            {
                foreach (var item in get)
                {
                    lstret.Add(ConvertPortModelToDto(item));
                }
            }

            return lstret;
        }
        /// <summary>
        /// Get list ports in VN
        /// </summary>
        /// <returns></returns>
        public List<PortDto> GetListPortInVN()
        {
            var lstret = new List<PortDto>();

            var get = (from o in eManifestModel.Ports
                       join s in eManifestModel.States on new { o.StateId } equals new { s.StateId }
                       where s.ShortName.Equals("VN")
                       orderby o.PortCode
                       select o);

            if (get != null)
            {
                foreach (var item in get)
                {
                    lstret.Add(ConvertPortModelToDto(item));
                }
            }

            return lstret;
        }
        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        public PortDto GetPortByCode(string code)
        {
            PortDto ret = null;

            var get = eManifestModel.GetPortByCode(code.Trim()).SingleOrDefault();
            if (get != null)
            {
                ret = ConvertPortModelToDto(get);
            }

            return ret;
        }

        /// <summary>
        /// Get list ports
        /// </summary>
        /// <returns></returns>
        public List<PortDto> GetListPort()
        {
            var lstret = new List<PortDto>();

            var get = (from o in eManifestModel.Ports
                       select o);

            if (get != null)
            {
                foreach (var item in get)
                {
                    lstret.Add(ConvertPortModelToDto(item));
                }
            }

            return lstret;
        }

        /// <summary>
        /// Get list ports
        /// </summary>
        /// <returns></returns>
        public Dictionary<Guid, PortDto> GetDicPortInUsed()
        {
            var lstret = new Dictionary<Guid, PortDto>();

            var get = (from o in eManifestModel.Ports
                       where o.IsInUsed == true
                       orderby o.PortCode
                       select o);

            if (get != null)
            {
                foreach (var item in get)
                {
                    lstret.Add(item.PortId, ConvertPortModelToDto(item));
                }
            }

            return lstret;
        }

        public Dictionary<string, PortDto> GetDicPortInUsed2()
        {
            var lstret = new Dictionary<string, PortDto>();

            var get = (from o in eManifestModel.Ports
                       where o.IsInUsed == true
                       orderby o.PortCode
                       select o);

            if (get != null)
            {
                foreach (var item in get)
                {
                    lstret.Add(item.PortCode.Trim(), ConvertPortModelToDto(item));
                }
            }

            return lstret;
        }

        #endregion

        #endregion

        #region ItemCode

        /// <summary>
        /// Convert from model object to dto object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private ItemCodeDto ConvertItemCodeModelToDto(ItemCode obj)
        {
            var ret = new ItemCodeDto
            {
                ItemCodeId = obj.ItemCodeId,
                HSCode = obj.HSCode,
                Name = obj.Name,
                Description = obj.Description,
                ItemId = obj.ItemId,
            };

            // Dangerous Good Item
            if (obj.ItemCodeVN != null)
            {
                ret.ItemCodeVN = ConvertItemCodeVNModelToDto(obj.ItemCodeVN);
            }

            return ret;
        }

        /// <summary>
        /// Convert from dto object to model object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private ItemCode ConvertItemCodeDtoToModel(ItemCodeDto obj)
        {
            var ret = new ItemCode
            {
                ItemCodeId = obj.ItemCodeId,
                HSCode = obj.HSCode,
                Name = obj.Name,
                Description = obj.Description,
                ItemId = obj.ItemId,
            };

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        private ItemCode GetItemCodeModelById(Guid id)
        {
            var ret = (from o in eManifestModel.ItemCodes
                       where o.ItemCodeId == id
                       select o).FirstOrDefault() as ItemCode;

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        public ItemCodeDto GetItemCodeById(Guid id)
        {
            ItemCodeDto ret = null;

            var get = GetItemCodeModelById(id);

            if (get != null)
            {
                ret = ConvertItemCodeModelToDto(get);
            }

            return ret;
        }

        /// <summary>
        /// Get id by HsCode
        /// </summary>
        /// <returns></returns>
        public Guid? GetItemCodeIdByHsCode(string hsCode)
        {
            Guid? ret = null;

            var get = (from o in eManifestModel.ItemCodes
                       where string.Compare(o.HSCode, hsCode, true) == 0
                       select o).FirstOrDefault() as ItemCode;

            if (get != null)
            {
                ret = get.ItemCodeId;
            }

            return ret;
        }

        /// <summary>
        /// Get list ItemCodes by ItemCode name
        /// </summary>
        /// <returns></returns>
        public List<ItemCodeDto> GetListItemCode()
        {
            var lstret = new List<ItemCodeDto>();

            var get = (from o in eManifestModel.ItemCodes
                       select o);

            if (get != null)
            {
                foreach (var item in get)
                {
                    lstret.Add(ConvertItemCodeModelToDto(item));
                }
            }

            return lstret;
        }

        /// <summary>
        /// Save ItemCode object
        /// </summary>
        /// <param name="itemCodeDto"></param>
        /// <returns></returns>
        public ResponseDto SaveItemCode(ItemCodeDto itemCodeDto)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                var get = GetItemCodeModelById(itemCodeDto.ItemCodeId);

                if (get != null)
                {
                    // Update
                    get.ItemCodeId = itemCodeDto.ItemCodeId;
                    get.HSCode = itemCodeDto.HSCode;
                    get.Name = itemCodeDto.Name;
                    get.Description = itemCodeDto.Description;
                    get.ItemId = itemCodeDto.ItemId;
                }
                else
                {
                    // Insert
                    get = ConvertItemCodeDtoToModel(itemCodeDto);
                    eManifestModel.ItemCodes.AddObject(get);
                }

                // Save change
                eManifestModel.SaveChanges();

            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Delete object by Id
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        public ResponseDto DeleteItemCode(Guid id)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                var get = GetItemCodeModelById(id);

                if (get != null)
                {
                    eManifestModel.ItemCodes.DeleteObject(get);
                }

                // Save change
                eManifestModel.SaveChanges();
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        #endregion

        #region Ship

        /// <summary>
        /// Convert from model object to dto object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private ShipDto ConvertShipModelToDto(Ship obj)
        {
            var ret = new ShipDto
            {
                ShipId = obj.ShipId,
                ShipName = obj.ShipName.Trim(),
                ShipTypeId = obj.ShipTypeId,
                IMONumber = obj.IMONumber.Trim(),
                CallSign = obj.CallSign.Trim(),
                StateId = obj.StateId,
                RegistryNumber = obj.RegistryNumber.Trim(),
                RegistryDate = obj.RegistryDate,
                RegistryPortId = obj.RegistryPortId,
                GrossWeight = obj.GrossWeight,
                NetWeight = obj.NetWeight,
                IsDelete = obj.IsDelete,
                CreaterId = obj.CreaterId,
                CreatedDate = obj.CreatedDate
            };

            //// Get ship type
            //if (obj.ShipType != null) ret.ShipType = ConvertShipTypeModelToDto(obj.ShipType);

            //// Get ship state
            //if (obj.State != null) ret.State = ConvertStateModelToDto(obj.State);

            return ret;
        }

        /// <summary>
        /// Convert from dto object to model object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private Ship ConvertShipDtoToModel(ShipDto obj)
        {
            var ret = new Ship
            {
                ShipId = obj.ShipId,
                ShipName = obj.ShipName.Trim(),
                ShipTypeId = obj.ShipTypeId,
                IMONumber = obj.IMONumber.Trim(),
                CallSign = obj.CallSign.Trim(),
                StateId = obj.StateId,
                RegistryNumber = obj.RegistryNumber.Trim(),
                RegistryDate = obj.RegistryDate,
                ShipAgencyId = obj.ShipAgencyId,
                RegistryPortId = obj.RegistryPortId,
                GrossWeight = obj.GrossWeight,
                NetWeight = obj.NetWeight,
                //IsDelete = obj.IsDelete.GetValueOrDefault(),
                IsDelete = false,
                CreaterId = obj.CreaterId,
                CreatedDate = obj.CreatedDate
            };

            return ret;
        }

        /// <summary>
        /// Get object model by id
        /// </summary>
        /// <returns></returns>
        private Ship GetShipModelById(Guid id)
        {
            var ret = (from o in eManifestModel.Ships
                       where o.ShipId == id
                       select o).FirstOrDefault() as Ship;

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        public ShipDto GetShipById(Guid id)
        {
            ShipDto ret = null;

            var get = GetShipModelById(id);

            if (get != null)
            {
                ret = ConvertShipModelToDto(get);
            }

            return ret;
        }

        /// <summary>
        /// Get list Ships by ship name
        /// </summary>
        /// <returns></returns>
        public List<ShipDto> GetListShip(string shipName)
        {
            var lstret = new List<ShipDto>();

            var get = (from o in eManifestModel.Ships
                       where string.Compare(o.ShipName, shipName, true) == 0
                       select o);

            if (get != null)
            {
                foreach (var item in get)
                {
                    lstret.Add(ConvertShipModelToDto(item));
                }
            }

            return lstret;
        }

        /// <summary>
        /// Get list Ships
        /// </summary>
        /// <returns></returns>
        public List<ShipDto> GetListShip()
        {
            var lstret = new List<ShipDto>();

            var get = (from o in eManifestModel.Ships
                       where (o.IsDelete.HasValue ? o.IsDelete.Value : false) == false
                       select o);

            if (get != null)
            {
                foreach (var item in get)
                {
                    lstret.Add(ConvertShipModelToDto(item));
                }
            }

            return lstret;
        }


        // <summary>
        /// Get list Ships By CreaterId
        /// </summary>
        /// <returns></returns>
        public List<ShipDto> GetListShipByCreaterId(Guid createrId)
        {
            var lstret = new List<ShipDto>();

            var get = (from o in eManifestModel.Ships
                       where o.CreaterId == createrId && (o.IsDelete.HasValue ? o.IsDelete.Value : false) == false
                       select o);

            if (get != null)
            {
                foreach (var item in get)
                {
                    lstret.Add(ConvertShipModelToDto(item));
                }
            }

            return lstret;
        }

        // <summary>
        /// Get list Ships By agencyId
        /// </summary>
        /// <returns></returns>
        public List<ShipDto> GetListShipByAgency(int agencyId)
        {
            var lstret = new List<ShipDto>();

            var get = (from o in eManifestModel.Ships
                       where o.ShipAgencyId == agencyId && (o.IsDelete.HasValue ? o.IsDelete.Value : false) == false
                       select o);

            if (get != null)
            {
                foreach (var item in get)
                {
                    lstret.Add(ConvertShipModelToDto(item));
                }
            }

            return lstret;
        }
        /// <summary>
        /// Save ship object
        /// </summary>
        /// <param name="shipDto"></param>
        /// <returns></returns>
        public ResponseDto SaveShip(ShipDto shipDto)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                var get = GetShipModelById(shipDto.ShipId);

                if (get != null)
                {
                    // Update
                    get.ShipId = shipDto.ShipId;
                    get.ShipName = shipDto.ShipName.Trim();
                    get.ShipTypeId = shipDto.ShipTypeId;
                    get.IMONumber = shipDto.IMONumber.Trim();
                    get.CallSign = shipDto.CallSign.Trim();
                    get.StateId = shipDto.StateId;
                    get.RegistryNumber = shipDto.RegistryNumber.Trim();
                    get.RegistryDate = shipDto.RegistryDate;
                    get.RegistryPortId = shipDto.RegistryPortId;
                    get.GrossWeight = shipDto.GrossWeight;
                    get.NetWeight = shipDto.NetWeight;
                    get.IsDelete = shipDto.IsDelete;
                    get.CreaterId = shipDto.CreaterId;
                    get.CreatedDate = shipDto.CreatedDate;
                    if (!get.ShipAgencyId.HasValue)
                        get.ShipAgencyId = shipDto.ShipAgencyId;
                }
                else
                {
                    // Insert
                    get = ConvertShipDtoToModel(shipDto);
                    eManifestModel.Ships.AddObject(get);
                }

                // Save change
                eManifestModel.SaveChanges();

            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Delete object by Id
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        public ResponseDto DeleteShip(Guid id)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                var get = GetShipModelById(id);

                if (get != null)
                {
                    eManifestModel.Ships.DeleteObject(get);
                }

                // Save change
                eManifestModel.SaveChanges();
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        #endregion

        #region Document

        /// <summary>
        /// Convert from model object to dto object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private DocumentDto ConvertDocumentModelToDto(Document obj, bool isNew = false)
        {
            var ret = new DocumentDto
            {
                DocumentId = obj.DocumentId,
                Name = obj.Name.Trim(),
                ShipId = obj.ShipId,
                PortId = obj.PortId,
                IsArrival = obj.IsArrival,
                ArrivalDate = obj.ArrivalDate,
                MasterName = obj.MasterName.Trim(),
                CreatedDate = obj.CreatedDate,
                LastModifiedDate = obj.LastModifiedDate,
                OwnerId = obj.OwnerId,
                IsDelete = obj.IsDelete,
                StatusId = obj.StatusId,
                StatusUpdate = obj.StatusUpdate,
                ValidDays = obj.ValidDays,
                DocumentTypeId = obj.DocumentTypeId,
                UploadType = enumUploadType.Original,
                FormsStatus = obj.FormsStatus.Trim()
            };

            //// Port
            //if (obj.PortId != null) ret.Port = ConvertPortModelToDto(obj.Port);
            // Ship
            //if (obj.ShipId != null) ret.Ship = ConvertShipModelToDto(obj.Ship);

            //// Status
            //if (obj.StatusId != null) ret.DocumentStatus = ConvertDocumentStatusModelToDto(obj.DocumentStatu);
            //// DocumentType
            //if (obj.DocumentTypeId != null) ret.DocumentType = ConvertDocumentTypeModelToDto(obj.DocumentType);

            if (!isNew)
            {
                //Document Change
                if (obj.DocumentChanges != null)
                    if (obj.DocumentChanges.Count > 0)
                    {
                        DocumentChange change = obj.DocumentChanges.OrderByDescending(s => s.CreatedDate).FirstOrDefault();
                        if (change != null)
                        {
                            ret.DocumentChange = new DocumentChangeDto
                                                     {
                                                         CreatedDate = change.CreatedDate,
                                                         CreaterId = change.CreaterId,
                                                         Description = change.Description,
                                                         DocumentChangeId = change.DocumentChangeId,
                                                         DocumentId = change.DocumentId,
                                                     };
                        }
                    }
            }
            //if (obj.GeneralDeclarations != null)
            //{
            //    //foreach (var item in obj.GeneralDeclarations)
            //    //{
            //    //    ret.GeneralDeclarations.Add(ConvertGeneralDeclarationModelToDto(item));
            //    //}
            //     ret.GeneralDeclarations.Add(ConvertGeneralDeclarationModelToDto(obj.GeneralDeclarations.ElementAt(0)));
            //}
            //if (obj.NoticeShip != null)
            //{
            //    NoticeShip notice = obj.NoticeShip;
            //    ret.NoticeShip = new NoticeShipToDto()
            //                         {
            //                             CreaterId = notice.CreaterId,
            //                             Description = notice.Description,
            //                             DocumentId = notice.DocumentId,
            //                             Time = notice.CreatedDate

            //                         };
            //}

            return ret;
        }

        /// <summary>
        /// Convert from model object to dto object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private DocumentDto ConvertAllDocumentModelToDto(Document obj, Nullable<Guid> userId, bool isAll = false)
        {
            var ret = new DocumentDto
            {
                DocumentId = obj.DocumentId,
                Name = obj.Name.Trim(),
                ShipId = obj.ShipId,
                PortId = obj.PortId,
                IsArrival = obj.IsArrival,
                ArrivalDate = obj.ArrivalDate,
                MasterName = obj.MasterName.Trim(),
                CreatedDate = obj.CreatedDate,
                LastModifiedDate = obj.LastModifiedDate,
                OwnerId = obj.OwnerId,
                IsDelete = obj.IsDelete,
                StatusId = obj.StatusId,
                DocumentTypeId = obj.DocumentTypeId,
                StatusUpdate = obj.StatusUpdate,
                ValidDays = obj.ValidDays,
                FormsStatus = obj.FormsStatus.Trim()
            };

          
            //// GeneralDeclarations
            if (isAll && obj.GeneralDeclarations != null)
            {
                foreach (var item in obj.GeneralDeclarations)
                {
                    ret.GeneralDeclarations.Add(ConvertGeneralDeclarationModelToDto(item));
                }
            }
           
            return ret;
        }

        /// <summary>
        /// Convert from dto object to model object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private Document ConvertDocumentDtoToModel(DocumentDto obj)
        {
            var ret = new Document
            {
                DocumentId = obj.DocumentId,
                Name = obj.Name.Trim(),
                ShipId = obj.ShipId,
                PortId = obj.PortId,
                IsArrival = obj.IsArrival,
                ArrivalDate = obj.ArrivalDate,
                MasterName = obj.MasterName.Trim(),
                CreatedDate = obj.CreatedDate,
                LastModifiedDate = obj.LastModifiedDate,
                OwnerId = obj.OwnerId,
                IsDelete = obj.IsDelete,
                StatusId = obj.StatusId,
                DocumentTypeId = obj.DocumentTypeId,
                FormsStatus = obj.FormsStatus.Trim()
            };

            return ret;
        }

        /// <summary>
        /// Get object model by id
        /// </summary>
        /// <returns></returns>
        private Document GetDocumentModelById(Guid id)
        {
            var ret = (from o in eManifestModel.Documents
                       where o.DocumentId == id && (o.IsDelete.HasValue ? o.IsDelete.Value : false) == false
                       select o).FirstOrDefault() as Document;

            return ret;
        }

        /// <summary>
        /// Check status submit of document
        /// </summary>
        /// <param name="documentId"></param>
        /// <returns></returns>
        private bool IsSubmitDocument(Guid documentId)
        {
            bool ret = false;

            var document = GetDocumentModelById(documentId);

            if (document != null)
            {
                if (document.StatusId >= 1)
                {
                    ret = true;
                }
            }

            return ret;
        }

        /// <summary>
        /// Check status submit of document
        /// </summary>
        /// <param name="documentId"></param>
        /// <returns></returns>
        private void GetDocument(Guid documentId, out bool isSubmit, out Guid ownerId)
        {
            isSubmit = false;
            ownerId = Guid.Empty;
            var document = GetDocumentModelById(documentId);

            if (document != null)
            {
                if (document.StatusId >= 1)
                {
                    isSubmit = true;
                }
                ownerId = document.OwnerId;
            }

        }
        /// <summary>
        /// Set status update for document
        /// </summary>
        /// <param name="documentId"></param>
        /// <returns></returns>
        private void SetDocumentStatusUpdate(Guid documentId, enumDocumentUpdate emUpdate)
        {
            var document = GetDocumentModelById(documentId);

            if (document != null)
            {
                //document.StatusUpdate = 1;

                // Add or update to document update table
                if (document.DocumentUpdate != null)
                {
                    document.DocumentUpdate.IsCrew |= (enumDocumentUpdate.Crew == emUpdate) ? true : false;
                    document.DocumentUpdate.IsCrewEffectDeclaration |= (enumDocumentUpdate.CrewEffectDeclaration == emUpdate) ? true : false;
                    document.DocumentUpdate.IsDangerousGoods |= (enumDocumentUpdate.DangerousGood == emUpdate) ? true : false;
                    document.DocumentUpdate.IsPassenger |= (enumDocumentUpdate.Passenger == emUpdate) ? true : false;
                    document.DocumentUpdate.IsGeneralDeclaration |= (enumDocumentUpdate.GeneralDeclaration == emUpdate) ? true : false;
                    document.DocumentUpdate.IsGoodDeclaration |= (enumDocumentUpdate.GoodDeclaration == emUpdate) ? true : false;
                    document.DocumentUpdate.IsShipStoreDeclaration |= (enumDocumentUpdate.ShipStoreDeclaration == emUpdate) ? true : false;
                    document.DocumentUpdate.IsHouseBill |= (enumDocumentUpdate.HouseBill == emUpdate) ? true : false;
                    document.DocumentUpdate.DateUpdate = DateTime.Now.ToString();
                }
                else
                {
                    var documentUpdate = new DocumentUpdate
                    {
                        DocumentId = documentId,
                        IsCrew = (enumDocumentUpdate.Crew == emUpdate) ? true : false,
                        IsCrewEffectDeclaration = (enumDocumentUpdate.CrewEffectDeclaration == emUpdate) ? true : false,
                        IsDangerousGoods = (enumDocumentUpdate.DangerousGood == emUpdate) ? true : false,
                        IsPassenger = (enumDocumentUpdate.Passenger == emUpdate) ? true : false,
                        IsGeneralDeclaration = (enumDocumentUpdate.GeneralDeclaration == emUpdate) ? true : false,
                        IsGoodDeclaration = (enumDocumentUpdate.GoodDeclaration == emUpdate) ? true : false,
                        IsShipStoreDeclaration = (enumDocumentUpdate.ShipStoreDeclaration == emUpdate) ? true : false,
                        IsHouseBill = (enumDocumentUpdate.HouseBill == emUpdate) ? true : false,
                        DateUpdate = DateTime.Now.ToString(),
                    };

                    // Add
                    document.DocumentUpdate = documentUpdate;
                }
            }
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        public DocumentDto GetDocumentById(Guid id)
        {
            DocumentDto ret = null;

            var get = GetDocumentModelById(id);

            if (get != null)
            {
                ret = ConvertAllDocumentModelToDto(get, null, false);
                //ret = ConvertDocumentModelToDto(get);
            }

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        public DocumentDto GetDocumentDetail(Guid documentId, Guid userId)
        {
            DocumentDto ret = null;

            var get = GetDocumentModelById(documentId);

            if (get != null)
            {
                ret = ConvertAllDocumentModelToDto(get, userId, true);
                //ret = ConvertDocumentModelToDto(get);
            }
            //var edi = GetLastEdiUploadFileByDocumentId(documentId, userId);
            //if (edi != null)
            //{
            //    if (edi.StatusAfterBatch.GetValueOrDefault(0) == 0)
            //    {
            //        //Not run yet. Must check if EDI file is exists or not
            //        //if file is exists ret.StatusAfterBatch = 1 else = 0
            //        ret.StatusAfterBatch = 0;
            //    }
            //    else if (edi.StatusAfterBatch.GetValueOrDefault(0) == 3)
            //    {
            //        //Error
            //        ret.StatusAfterBatch = 3;
            //    }
            //    else
            //    {
            //        //OR ??
            //        ret.StatusAfterBatch = 2;
            //    }
            //}
            //else
            //    ret.StatusAfterBatch = 2;
            return ret;
        }

        /// <summary>
        /// Get list Documents by Document name
        /// </summary>
        /// <returns></returns>
        public List<DocumentDto> GetListDocument(string name)
        {
            var lstret = new List<DocumentDto>();

            var get = (from o in eManifestModel.Documents
                       where string.Compare(o.Name, name, true) == 0 && (o.IsDelete.HasValue ? o.IsDelete.Value : false) == false
                       select o);

            if (get != null)
            {
                foreach (var item in get)
                {
                    lstret.Add(ConvertDocumentModelToDto(item));
                }
            }

            return lstret;
        }

        /// <summary>
        /// Get list Documents
        /// </summary>
        /// <returns></returns>
        public List<DocumentDto> GetListDocument()
        {
            var lstret = new List<DocumentDto>();

            var get = (from o in eManifestModel.Documents
                       where (o.IsDelete.HasValue ? o.IsDelete.Value : false) == false
                       select o);

            if (get != null)
            {
                foreach (var item in get)
                {
                    lstret.Add(ConvertDocumentModelToDto(item));
                }
            }

            return lstret;
        }

        /// <summary>
        /// Get list Documents By CreaterId
        /// </summary>
        /// <returns></returns>
        public List<DocumentDto> GetListDocumentByUserId(Guid userId, bool isNew = false)
        {
            var lstret = new List<DocumentDto>();
            var dt = DateTime.Now.AddDays(-100);

            var get = (from o in eManifestModel.Documents
                       join ud in eManifestModel.UsersInDocuments on new { o.DocumentId } equals new { ud.DocumentId }
                       where (o.IsDelete.HasValue ? o.IsDelete.Value : false) == false
                        && (isNew == false || o.StatusId <= 3)
                        && (/*(o.OwnerId == userId) || */(ud.UserId == userId && (ud.AccessForms.HasValue && ud.AccessForms.Value > 0)))
                        && o.CreatedDate > dt
                       orderby o.CreatedDate descending
                       select new { o, ud.AccessForms }).Take(50);

            if (get != null)
            {
                foreach (var item in get)
                {
                    DocumentDto doc = ConvertDocumentModelToDto(item.o, isNew);
                    doc.FormsStatus = item.AccessForms.ToString();
                    lstret.Add(doc);
                }
            }

            return lstret;
        }

        /// <summary>
        /// Save Document object
        /// </summary>
        /// <param name="documentDto"></param>
        /// <returns></returns>
        public ResponseDto SaveDocument(DocumentDto documentDto)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                var get = GetDocumentModelById(documentDto.DocumentId);

                if (get != null)
                {
                    // Update
                    if (documentDto.PortId != Guid.Empty)
                        get.PortId = documentDto.PortId;
                    get.IsArrival = documentDto.IsArrival;
                    if (documentDto.IsArrival)
                    {
                        get.ArrivalDate = documentDto.ArrivalDate;
                    }
                    if (!string.IsNullOrEmpty(documentDto.MasterName))
                        get.MasterName = documentDto.MasterName;
                    if (documentDto.CreatedDate != DateTime.MinValue)
                        get.CreatedDate = documentDto.CreatedDate;
                    get.LastModifiedDate = documentDto.LastModifiedDate;
                    if (documentDto.IsDelete.HasValue)
                        get.IsDelete = documentDto.IsDelete.Value;
                    if (documentDto.StatusId.HasValue)
                    {
                        if (get.StatusId < documentDto.StatusId.Value)
                            get.StatusId = documentDto.StatusId.Value;
                    }
                    if (documentDto.DocumentTypeId.HasValue)
                    {
                        get.DocumentTypeId = documentDto.DocumentTypeId.Value;
                    }
                    if (!string.IsNullOrEmpty(documentDto.FormsStatus))
                        get.FormsStatus = documentDto.FormsStatus;

                    if (documentDto.ShipId != Guid.Empty)
                        get.ShipId = documentDto.ShipId;

                    // Updagte to history
                    //UpdateDocumentHistory(documentDto, false);
                }
                else
                {
                    // Insert           
                    DateTime dt = DateTime.Now;
                    int preNo = eManifestModel.Documents.Count(row => row.CreatedDate.Year == dt.Year);
                    documentDto.Name = string.Format("{0}/{1}", preNo.ToString("D4"), dt.Year.ToString());

                    get = ConvertDocumentDtoToModel(documentDto);
                    eManifestModel.Documents.AddObject(get);

                    // Insert to history
                    UpdateDocumentHistory(documentDto, true);
                }

                // Save change
                eManifestModel.SaveChanges();

            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        public ResponseDto UpdateDocumentStatus(Guid documentId, int statusId)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                var get = GetDocumentModelById(documentId);

                if (get != null)
                {
                    if (get.DocumentChanges != null && get.DocumentChanges.Count > 0)
                    {
                        get.StatusUpdate = 1;
                    }

                    get.StatusId = statusId;
                    get.LastModifiedDate = DateTime.Now;
                    // Save change
                    var his = new DocumentHistory
                    {
                        DocumentHistoryId = Guid.NewGuid(),
                        DocumentId = get.DocumentId,
                        ModifiedDate = null, //DateTime.Now, //Get GMT time. May be change time = database time by trigger
                        StatusId = statusId,
                        UserID = get.OwnerId,
                        Description = "Submit",
                        StatusUpdate = get.DocumentChanges != null && get.DocumentChanges.Count > 0 ? 1 : 0,
                        StatusProcessUpdate = 0
                        //UserID = obj.CreaterId
                        //UserInfomation = obj.UserInfomation
                        //Result = documentDto.Result,
                        //StatusUpdate =documentDto.StatusUpdate,
                        //StatusProcessUpdate = documentDto.StatusProcessUpdate,
                        //DescriptionAllowUpdate = documentDto.DescriptionAllowUpdate,
                        //UserID = documentDto.UserInfomation.UserId,
                        //Description = documentDto.DescriptionUpdate,
                    };
                    eManifestModel.DocumentHistories.AddObject(his);

                   // var getDocument = GetDocumentModelById(shipStoreDeclarationDto.DocumentId);
                    SaveDocumentHistory(get, Guid.NewGuid() , string.Empty, " Gửi hồ sơ tớ hải quan ");
                    
                    eManifestModel.SaveChanges();
                }
                else
                {
                    ret.ErroeMessage = "No document is found";
                }
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Delete object by Id
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        public ResponseDto DeleteDocument(Guid id, Guid userId)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                var get = GetDocumentModelById(id);

                if (get != null && get.OwnerId == userId)
                {
                    get.IsDelete = true;

                    //// Delete general
                    //DeleteGeneralDeclarationByDocumentId_Sub(get.DocumentId);

                    //// Delete good declaration
                    //DeleteGoodDeclarationByDocumentId_Sub(get.DocumentId);

                    //// Delete dangerous good
                    //DeleteDangerousGoodByDocumentId_Sub(get.DocumentId);

                    //// Ship declaration
                    //DeleteShipStoreDeclarationByDocumentId_Sub(get.DocumentId);

                    //// Delete crew
                    //DeleteCrewByDocumentId_Sub(get.DocumentId);

                    //// Delete crew effect
                    //DeleteCrewEffectDeclarationByDocumentId_Sub(get.DocumentId);

                    //// Delete passenger
                    //DeletePassengerByDocumentId_Sub(get.DocumentId);

                    //// Delecte document
                    //eManifestModel.Documents.DeleteObject(get);

                    // Save change
                    eManifestModel.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Assign user to document
        /// </summary>
        /// <param name="docId">Document Id</param>
        /// <param name="userIDs">List of UserId</param>
        /// <returns></returns>
        public ResponseDto AddUsersToDocument2(Guid docId, List<UserInfomation> lstUserInfo)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };
            //Delete all userId first
            var q = (from o in eManifestModel.UsersInDocuments
                     where o.DocumentId == docId
                     select o);
            foreach (var o in q)
            {
                eManifestModel.UsersInDocuments.DeleteObject(o);
            }
            // Save change
            eManifestModel.SaveChanges();

            foreach (UserInfomation userInfo in lstUserInfo)
            {
                var get = new UsersInDocument
                {
                    UserId = userInfo.UserId,
                    AccessForms = userInfo.AccessForm,
                    DocumentId = docId
                };
                eManifestModel.UsersInDocuments.AddObject(get);
            }

            // Save change
            eManifestModel.SaveChanges();
            return ret;
        }
        public ResponseDto AddUsersToDocument(Guid docId, List<UserInfomation> lstUserInfo)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };
            DataTable dt = new DataTable();
            dt.Columns.Add("DocumentId", typeof(Guid));
            dt.Columns.Add("UserId", typeof(Guid));
            dt.Columns.Add("AccessForms", typeof(int));
            lstUserInfo.ForEach(u => dt.Rows.Add(docId, u.UserId, u.AccessForm));

            System.Data.SqlClient.SqlParameter param0 = new System.Data.SqlClient.SqlParameter { ParameterName = "@Users", TypeName = "[dbo].[UsersInDocumentType]", SqlDbType = System.Data.SqlDbType.Structured };
            param0.Value = dt;

            //System.Data.SqlClient.SqlParameter param1 = new System.Data.SqlClient.SqlParameter { ParameterName = "1", TypeName = "uniqueidentifier", SqlDbType = System.Data.SqlDbType.UniqueIdentifier };
            //SqlParameter stations = new SqlParameter { ParameterName = "p0", Value = ids, TypeName = "[dbo].[IdTable]", SqlDbType = SqlDbType.Structured };

            var parameters = new object[] { param0 };

            //var results = projectEntities.ExecuteStoreQuery<ProjectSummary>("exec ProjectSummary @p0", parameters);
            eManifestModel.ExecuteStoreCommand("eManifest_SaveUsersInDocuments @Users", parameters);
            return ret;
        }
        /// <summary>
        /// get list of user who was assigned to document
        /// </summary>
        /// <param name="docId">Document Id</param>        
        /// <returns>List of UserId</returns>
        public List<UserInfomation> GetListUserInDocument(Guid docId)
        {
            List<UserInfomation> lst = new List<UserInfomation>();
            var q = (from o in eManifestModel.UsersInDocuments
                     where o.DocumentId == docId && o.AccessForms > 0
                     select o);
            foreach (var o in q)
            {
                //lst.Add(o.UserId);
                lst.Add(new UserInfomation
                {
                    UserId = o.UserId,
                    AccessForm = o.AccessForms.GetValueOrDefault(),
                });
            }

            return lst;
        }

        public UserInfomation GetUserInfoByDocumentId(Guid docId, Guid userId)
        {
            UserInfomation userInfo = null;
            var q = (from o in eManifestModel.UsersInDocuments
                     where o.DocumentId == docId && o.UserId == userId
                     select o).FirstOrDefault();
            if (q != null)
            {
                userInfo = new UserInfomation
                {
                    UserId = q.UserId,
                    AccessForm = q.AccessForms.GetValueOrDefault(),
                };
            }

            return userInfo;
        }
        #endregion

        #region Document History

        /// <summary>
        /// CuongVC: Insert Document History
        /// </summary>
        /// <param name="documentDto">documentDto object</param>
        /// <param name="isNew"> documentDto is insert: true</param>
        private void UpdateDocumentHistory(DocumentDto documentDto, bool isNew)
        {
            if (documentDto == null)
                return;

            //var documentHistoryDto = new DocumentHistoryDto
            //{
            //    DocumentHistoryId = Guid.NewGuid(),
            //    DocumentId = documentDto.DocumentId,
            //    ModifiedDate = documentDto.LastModifiedDate, //Get time insert. May be change time = database time by trigger or by GMT time: DateTime.UtcNow
            //    //StatusId = documentDto.StatusId.HasValue?documentDto.StatusId.Value:-1,
            //    StatusId = isNew ? 0 : 1,
            //    //UserId = documentDto.OwnerId,
            //    Description = isNew ? "New" : "Update",
            //    //CreaterName = documentDto.UserInfomation != null ? documentDto.UserInfomation.UserName : string.Empty,
            //    //UserInfomation = documentDto.UserInfomation
            //    //Result = documentDto.Result,
            //    //StatusUpdate = documentDto.StatusUpdate,
            //    //StatusProcessUpdate = documentDto.StatusProcessUpdate,
            //    //DescriptionAllowUpdate = documentDto.DescriptionAllowUpdate,
            //    //UserID = documentDto.UserInfomation.UserId,
            //    //Description = documentDto.DescriptionUpdate,               
            //};

            //var get = ConvertDocumentHistoryDtoToModel(documentHistoryDto);
            var get = new DocumentHistory
            {
                DocumentHistoryId = Guid.NewGuid(),
                DocumentId = documentDto.DocumentId,
                //Tanps add
                ModifiedDate = DateTime.Now, //Get time insert. May be change time = database time by trigger or by GMT time: DateTime.UtcNow
                //StatusId = documentDto.StatusId.HasValue?documentDto.StatusId.Value:-1,
                StatusId = documentDto.StatusId.HasValue ? documentDto.StatusId.Value : 0,
                UserID = documentDto.OwnerId, //Tanps
                Description = isNew ? "Tạo mới hồ sơ" : "Cập nhật hồ sơ"
            };
            eManifestModel.DocumentHistories.AddObject(get);
        }

        /// <summary>
        /// Convert from dto object to model object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private DocumentHistory ConvertDocumentHistoryDtoToModel(DocumentHistoryDto obj)
        {
            var ret = new DocumentHistory
            {
                DocumentHistoryId = obj.DocumentHistoryId,
                DocumentId = obj.DocumentId,
                //Tanps add
                ModifiedDate = DateTime.Now,  //Get GMT time. May be change time = database time by trigger

                StatusId = obj.StatusId,
                //CreaterName = obj.CreaterName,
                UserID = obj.UserId,  //Tanps
                Description = obj.Description
                //UserID = obj.CreaterId
                //UserInfomation = obj.UserInfomation
                //Result = documentDto.Result,
                //StatusUpdate =documentDto.StatusUpdate,
                //StatusProcessUpdate = documentDto.StatusProcessUpdate,
                //DescriptionAllowUpdate = documentDto.DescriptionAllowUpdate,
                //UserID = documentDto.UserInfomation.UserId,
                //Description = documentDto.DescriptionUpdate,
            };

            return ret;
        }

        /// <summary>
        /// Convert from model object to dto object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private DocumentHistoryDto ConvertDocumentHistoryModelToDto(DocumentHistory obj)
        {

            DocumentHistoryDto ret = null;
            if (obj != null)
                ret = new DocumentHistoryDto
                {
                    DocumentHistoryId = obj.DocumentHistoryId,
                    DocumentId = obj.DocumentId,
                    ModifiedDate = obj.ModifiedDate.Value, //Get GMT time. May be change time = database time by trigger
                    StatusId = obj.StatusId,
                    UserId = obj.UserID,
                    Description = obj.Description,
                    CreaterName = obj.CreaterName
                };

            return ret;
        }

        /// <summary>
        /// Get object model by id
        /// </summary>
        /// <returns></returns>
        private DocumentHistory GetDocumentHistoryModelById(Guid id)
        {
            var ret = (from o in eManifestModel.DocumentHistories
                       where o.DocumentHistoryId == id
                       select o).FirstOrDefault() as DocumentHistory;
            return ret;
        }

        /// <summary>
        /// Get object model by id
        /// </summary>
        /// <returns></returns>
        private DocumentHistory GetDocumentHistoryModel(Guid documentid, int statusId)
        {
            if (statusId == 8 || statusId == 9)
            {
                return (from o in eManifestModel.DocumentHistories
                        where o.DocumentId == documentid && o.StatusId == statusId && (o.StatusUpdate.HasValue ? o.StatusUpdate.Value == 0 : true)
                        orderby o.ModifiedDate descending
                        select o).FirstOrDefault() as DocumentHistory;
            }
            else
            {
                if (statusId == 2)
                    return (from o in eManifestModel.DocumentHistories
                            where o.DocumentId == documentid && o.StatusProcessUpdate == 3
                            orderby o.ModifiedDate descending
                            select o).FirstOrDefault() as DocumentHistory;
                else if (statusId == 3)
                    return (from o in eManifestModel.DocumentHistories
                            where o.DocumentId == documentid && (o.StatusProcessUpdate == 2 || o.StatusProcessUpdate == 4)
                            orderby o.ModifiedDate descending
                            select o).FirstOrDefault() as DocumentHistory;
            }
            return null;
        }

        /// <summary>
        /// Get document history by document id and status
        /// </summary>
        /// <param name="documentId"></param>
        /// <param name="statusId"></param>
        /// <returns></returns>
        public DocumentHistoryDto GetDocumentHistory(Guid documentId, int statusId)
        {
            var docHis = GetDocumentHistoryModel(documentId, statusId);
            return ConvertDocumentHistoryModelToDto(docHis);
        }
        public List<DocumentHistoryDto> GetListDocumentHistoryByDocId(Guid documentId, Guid userId)
        {

            List<DocumentHistoryDto> lstret = new List<DocumentHistoryDto>();
            //var ret = (from o in eManifestModel.Documents where o.DocumentId == documentId && o.OwnerId == userId select o.OwnerId).FirstOrDefault();
            var ret = GetDocumentModelById(documentId);
            if (ret != null)
                if (ret.OwnerId == userId)
                {
                    var get = (from o in eManifestModel.DocumentHistories
                               where o.DocumentId == documentId && o.StatusUpdate.HasValue == false && o.ModifiedDate != null
                               orderby o.ModifiedDate
                               select o);

                    if (get != null)
                    {
                        foreach (var item in get)
                        {
                            DocumentHistoryDto doc = ConvertDocumentHistoryModelToDto(item);
                            lstret.Add(doc);
                        }
                    }
                }
                else
                {
                    var get = (from o in eManifestModel.DocumentHistories
                               where o.DocumentId == documentId && o.StatusUpdate.HasValue == false && o.ModifiedDate != null && o.UserID == userId
                               orderby o.ModifiedDate
                               select o);

                    if (get != null)
                    {
                        foreach (var item in get)
                        {
                            DocumentHistoryDto doc = ConvertDocumentHistoryModelToDto(item);
                            lstret.Add(doc);
                        }
                    }
                }
            return lstret;
        }

        /// <summary>
        /// CuongVC: Insert Document History
        /// </summary>
        /// <param name="documentDto">documentDto object</param>
        /// <param name="isNew"> documentDto is insert: true</param>
        public void SaveDocumentHistory(Document doc, Guid userId, string userName, string description)
        {
            if (doc == null || doc.DocumentId == null || doc.DocumentId == Guid.Empty)
                return;

            //var documentHistoryDto = new DocumentHistoryDto
            //{
            //    DocumentHistoryId = Guid.NewGuid(),
            //    DocumentId = documentDto.DocumentId,
            //    ModifiedDate = DateTime.Now, //Get time insert. May be change time = database time by trigger or by GMT time: DateTime.UtcNow
            //    StatusId = documentDto.StatusId.Value,
            //    UserId = userId,
            //    CreaterName = userName,
            //    Description = description,                              
            //};
            var ret = new DocumentHistory
            {
                DocumentHistoryId = Guid.NewGuid(),
                DocumentId = doc.DocumentId,
                ModifiedDate = DateTime.Now, //Get GMT time. May be change time = database time by trigger
                StatusId = doc.StatusId.Value,
                CreaterName = userName,
                UserID = userId,
                Description = description
                //UserInfomation = obj.UserInfomation
                //Result = documentDto.Result,
                //StatusUpdate =documentDto.StatusUpdate,
                //StatusProcessUpdate = documentDto.StatusProcessUpdate,
                //DescriptionAllowUpdate = documentDto.DescriptionAllowUpdate,
                //UserID = documentDto.UserInfomation.UserId,
                //Description = documentDto.DescriptionUpdate,
            };

            //var get = ConvertDocumentHistoryDtoToModel(documentHistoryDto);
            eManifestModel.DocumentHistories.AddObject(ret);
        }

        #endregion
       

        #region GeneralDeclaration

        /// <summary>
        /// Convert from model object to dto object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private GeneralDeclarationDto ConvertGeneralDeclarationModelToDto(GeneralDeclaration obj)
        {
            var ret = new GeneralDeclarationDto
            {
                GeneralDeclarationId = obj.GeneralDeclarationId,
                DocumentId = obj.DocumentId,
                DeparturePortId = obj.DeparturePortId,
                LastArrivalPortId = obj.LastArrivalPortId,
                LastArrivalPortName = obj.LastArrivalPortName,
                DateOfArrival = obj.DateOfArrival,
                ContactDetails = obj.ContactDetails,
                PreviousPorts = obj.PreviousPorts,
                SubsequentPorts = obj.SubsequentPorts,
                ParticularsOfVoyage = obj.ParticularsOfVoyage,
                PositionInPort = obj.PositionInPort,
                DescriptionOfCargo = obj.DescriptionOfCargo,
                NumberOfCrews = obj.NumberOfCrews,
                NumberOfPassengers = obj.NumberOfPassengers,
                Remarks = obj.Remarks,
                Requirements = obj.Requirements,
                ModifiedDate = obj.ModifiedDate,
                CreaterId = obj.CreaterId,
                ItemStatus = obj.ItemStatus,
                ModifyId = obj.ModifyId,
                IsTemp = obj.IsTemp,
                UploadType = enumUploadType.Original

            };
            //if (obj.DeparturePortId != null) ret.DeparturePort = ConvertPortModelToDto(obj.Port);
            return ret;
        }

        /// <summary>
        /// Convert from dto object to model object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private GeneralDeclaration ConvertGeneralDeclarationDtoToModel(GeneralDeclarationDto obj)
        {
            var ret = new GeneralDeclaration
            {
                GeneralDeclarationId = obj.GeneralDeclarationId,
                DocumentId = obj.DocumentId,
                DeparturePortId = obj.DeparturePortId,
                LastArrivalPortId = obj.LastArrivalPortId,
                LastArrivalPortName = obj.LastArrivalPortName,
                DateOfArrival = obj.DateOfArrival,
                ContactDetails = obj.ContactDetails,
                PreviousPorts = obj.PreviousPorts,
                SubsequentPorts = obj.SubsequentPorts,
                ParticularsOfVoyage = obj.ParticularsOfVoyage,
                PositionInPort = obj.PositionInPort,
                DescriptionOfCargo = obj.DescriptionOfCargo,
                NumberOfCrews = obj.NumberOfCrews,
                NumberOfPassengers = obj.NumberOfPassengers,
                Remarks = obj.Remarks,
                Requirements = obj.Requirements,
                ModifiedDate = obj.ModifiedDate,
                CreaterId = obj.CreaterId,
                ItemStatus = obj.ItemStatus,
                ModifyId = obj.ModifyId,
                IsTemp = obj.IsTemp,
            };

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        private GeneralDeclaration GetGeneralDeclarationModelById(Guid id)
        {
            var ret = (from o in eManifestModel.GeneralDeclarations
                       where o.GeneralDeclarationId == id
                       select o).FirstOrDefault() as GeneralDeclaration;

            return ret;
        }

        /// <summary>
        /// Get object by document id and user id
        /// </summary>
        /// <returns></returns>
        private GeneralDeclaration GetGeneralDeclarationModelByDocumentId(Guid documentId, Guid userId, bool isTemp)
        {
            var ret = (from o in eManifestModel.GeneralDeclarations
                       where o.DocumentId == documentId && o.CreaterId == userId && o.IsTemp == isTemp
                       select o).FirstOrDefault() as GeneralDeclaration;

            return ret;
        }

        /// <summary>
        /// Delete object by document Id
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        private void DeleteGeneralDeclaration_Sub(Guid id)
        {
            var get = GetGeneralDeclarationModelById(id);

            if (get != null)
            {
                eManifestModel.GeneralDeclarations.DeleteObject(get);
            }
        }

        /// <summary>
        /// Delete object by document Id
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        private void DeleteGeneralDeclarationByDocumentId_Sub(Guid documentId)
        {
            var get = (from o in eManifestModel.GeneralDeclarations
                       where o.DocumentId == documentId
                       select o).ToList();

            if (get != null)
            {
                foreach (var item in get)
                {
                    DeleteGeneralDeclaration_Sub(item.GeneralDeclarationId);
                }
            }
        }

        /// <summary>
        /// Save GeneralDeclaration object
        /// </summary>
        /// <param name="generalDeclaration"></param>
        /// <returns></returns>
        private void SaveGeneralDeclaration_Sub(GeneralDeclarationDto generalDeclaration)
        {
            Document document = GetDocumentModelById(generalDeclaration.DocumentId);
            generalDeclaration.IsTemp = document != null && document.StatusId >= 1 ? true : false; //generalDeclaration.IsTemp = IsSubmitDocument(generalDeclaration.DocumentId);

            // Update document status
            if (generalDeclaration.IsTemp)
            {
                SetDocumentStatusUpdate(generalDeclaration.DocumentId, enumDocumentUpdate.GeneralDeclaration);
            }
            
            generalDeclaration.DateOfArrival = document.ArrivalDate; // Copy from Document

            var get = GetGeneralDeclarationModelByDocumentId(generalDeclaration.DocumentId, generalDeclaration.CreaterId, generalDeclaration.IsTemp);

            if (get != null)
            {
                // Update
                // get.GeneralDeclarationId = generalDeclaration.GeneralDeclarationId;
                get.DeparturePortId = generalDeclaration.DeparturePortId;
                get.LastArrivalPortId = generalDeclaration.LastArrivalPortId;
                get.DateOfArrival = generalDeclaration.DateOfArrival;
                get.ContactDetails = generalDeclaration.ContactDetails;
                get.PreviousPorts = generalDeclaration.PreviousPorts;
                get.SubsequentPorts = generalDeclaration.SubsequentPorts;
                get.ParticularsOfVoyage = generalDeclaration.ParticularsOfVoyage;
                get.PositionInPort = generalDeclaration.PositionInPort;
                get.DescriptionOfCargo = generalDeclaration.DescriptionOfCargo;
                get.NumberOfCrews = generalDeclaration.NumberOfCrews;
                get.NumberOfPassengers = generalDeclaration.NumberOfPassengers;
                get.Remarks = generalDeclaration.Remarks;
                get.Requirements = generalDeclaration.Requirements;
                get.ModifiedDate = generalDeclaration.ModifiedDate;
                get.CreaterId = generalDeclaration.CreaterId;
                get.ItemStatus = generalDeclaration.ItemStatus;
                get.DocumentId = generalDeclaration.DocumentId;
                get.ModifyId = generalDeclaration.ModifyId;
                get.IsTemp = generalDeclaration.IsTemp;
            }
            else
            {
                // Insert
                get = ConvertGeneralDeclarationDtoToModel(generalDeclaration);
                eManifestModel.GeneralDeclarations.AddObject(get);
            }
        }

        /// <summary>
        /// Delete object by documentId
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        private void DeleteGeneralDeclarationByDocumentId_Sub(Guid documentId, Guid createrId, bool isTemp)
        {
            var get = (from o in eManifestModel.GeneralDeclarations
                       where o.DocumentId == documentId && o.IsTemp == isTemp && (createrId == Guid.Empty ? true : o.CreaterId == createrId)
                       select o);

            if (get == null) return;

            List<Guid> lstGuidId = new List<Guid>();
            foreach (var item in get)
            {
                lstGuidId.Add(item.GeneralDeclarationId);
            }

            foreach (var id in lstGuidId)
            {
                DeleteGeneralDeclaration_Sub(id);
            }
        }

        /// <summary>
        /// Delete object by documentId
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        private ResponseDto DeleteGeneralDeclarationByDocumentId(Guid documentId, bool isTemp = false)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                DeleteGeneralDeclarationByDocumentId_Sub(documentId, Guid.Empty, isTemp);

                // Save change
                eManifestModel.SaveChanges();
            }

            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Delete object by documentId and userId
        /// </summary>
        /// <param name="documentId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public ResponseDto DeleteGeneralDeclarationByDocumentId(Guid documentId, Guid userId)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            eManifestModel.DeleteGeneralDeclaration(documentId, userId);

            return ret;
        }

        /// <summary>
        /// Get list GeneralDeclarations by GeneralDeclaration name
        /// </summary>
        /// <returns></returns>
        public List<GeneralDeclarationDto> GetListGeneralDeclaration(Guid documentId, bool isTemp = false)
        {
            var lstret = new List<GeneralDeclarationDto>();

            var get = (from o in eManifestModel.GeneralDeclarations
                       where o.DocumentId == documentId && o.IsTemp == isTemp
                       select o);

            if (get != null)
            {
                foreach (var item in get)
                {
                    lstret.Add(ConvertGeneralDeclarationModelToDto(item));
                }
            }

            return lstret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        public GeneralDeclarationDto GetGeneralDeclarationById(Guid id)
        {
            GeneralDeclarationDto ret = null;

            var get = GetGeneralDeclarationModelById(id);

            if (get != null)
            {
                ret = ConvertGeneralDeclarationModelToDto(get);
            }

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        public GeneralDeclarationDto GetGeneralDeclarationByDocumentId(Guid documentId, Guid userId)
        {
            GeneralDeclarationDto ret = null;

            // Get from temp
            var get = (from o in eManifestModel.GeneralDeclarations
                       where o.DocumentId == documentId && o.CreaterId == userId && o.IsTemp == true
                       select o).FirstOrDefault() as GeneralDeclaration;

            if (get != null)
            {
                ret = ConvertGeneralDeclarationModelToDto(get);
                return ret;
            }

            // Get from submited
            get = (from o in eManifestModel.GeneralDeclarations
                   where o.DocumentId == documentId && o.CreaterId == userId && o.IsTemp == false
                   select o).FirstOrDefault() as GeneralDeclaration;

            if (get != null)
            {
                ret = ConvertGeneralDeclarationModelToDto(get);
            }

            return ret;
        }

        /// <summary>
        /// Save GeneralDeclaration object
        /// </summary>
        /// <param name="generalDeclaration"></param>
        /// <returns></returns>
        public ResponseDto SaveGeneralDeclaration(GeneralDeclarationDto generalDeclaration)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                // Save
                SaveGeneralDeclaration_Sub(generalDeclaration);

                // Save change
                eManifestModel.SaveChanges();

            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Delete object by Id
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        public ResponseDto DeleteGeneralDeclaration(Guid documentId)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                DeleteGeneralDeclaration_Sub(documentId);

                // Save change
                eManifestModel.SaveChanges();
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        #endregion

        #region DangerousGood

        /// <summary>
        /// Convert from model object to dto object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private DangerousGoodDto ConvertDangerousGoodModelToDto(DangerousGood obj, bool isAll = true)
        {
            var ret = new DangerousGoodDto
            {
                DangerousGoodId = obj.DangerousGoodId,
                DocumentId = obj.DocumentId,
                PortOfLoad = obj.PortOfLoad,
                PortOfUnload = obj.PortOfUnload,
                PortNameOfLoad = obj.PortNameOfLoad,
                PortNameOfUnload = obj.PortNameOfUnload,
                ContNumber = obj.ContNumber,
                ContSealNumber = obj.ContSealNumber,
                ItemStatus = obj.ItemStatus,
                CreatedDate = obj.CreatedDate,
                CreaterId = obj.CreaterId,
                ModifyId = obj.ModifyId,
                IsTemp = obj.IsTemp,
                UploadType = enumUploadType.Original
            };

            //if (obj.PortOfLoad != null) ret.PortDtoOfLoad = ConvertPortModelToDto(obj.Port);

            // Dangerous Good Item
            if (isAll & obj.DangerousGoodItems != null)
            {
                ret.DangerousGoodItems = new List<DangerousGoodItemDto>();
                foreach (var item in obj.DangerousGoodItems)
                {
                    ret.DangerousGoodItems.Add(ConvertDangerousGoodItemModelToDto(item));
                }
            }

            return ret;
        }

        /// <summary>
        /// Convert from dto object to model object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private DangerousGood ConvertDangerousGoodDtoToModel(DangerousGoodDto obj)
        {
            var ret = new DangerousGood
            {
                DangerousGoodId = obj.DangerousGoodId,
                PortOfLoad = obj.PortOfLoad,
                PortOfUnload = obj.PortOfUnload,
                PortNameOfLoad = obj.PortNameOfLoad,
                PortNameOfUnload = obj.PortNameOfUnload,
                ContNumber = obj.ContNumber,
                ContSealNumber = obj.ContSealNumber,
                ItemStatus = obj.ItemStatus,
                CreatedDate = obj.CreatedDate,
                CreaterId = obj.CreaterId,
                DocumentId = obj.DocumentId,
                ModifyId = obj.ModifyId,
                IsTemp = obj.IsTemp,
            };

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        private DangerousGood GetDangerousGoodModelById(Guid id)
        {
            var ret = (from o in eManifestModel.DangerousGoods
                       where o.DangerousGoodId == id
                       select o).FirstOrDefault() as DangerousGood;

            return ret;
        }

        /// <summary>
        /// Get object by document id and user id
        /// </summary>
        /// <returns></returns>
        private DangerousGood GetDangerousGoodModelByDocumentId(Guid documentId, Guid? userId, bool isTemp)
        {
            var ret = (from o in eManifestModel.DangerousGoods
                       where o.DocumentId == documentId && o.CreaterId == userId && o.IsTemp == isTemp
                       select o).FirstOrDefault() as DangerousGood;

            return ret;
        }
        private DangerousGood GetDangerousGoodModelByContainerNo(Guid documentId, Guid? userId, string containerNo, bool isTemp)
        {
            var ret = (from o in eManifestModel.DangerousGoods
                       where o.DocumentId == documentId && o.CreaterId == userId && containerNo.Trim().Equals(o.ContNumber.Trim()) && o.IsTemp == isTemp
                       select o).FirstOrDefault() as DangerousGood;

            return ret;
        }
        /// <summary>
        /// Delete object by Id
        /// </summary>
        /// <param name="dangerousGoodId"></param>
        /// <returns></returns>
        private void DeleteDangerousGood_Sub(Guid dangerousGoodId)
        {
            var get = GetDangerousGoodModelById(dangerousGoodId);

            if (get != null)
            {
                // Delete good items
                if (get.DangerousGoodItems != null)
                {
                    List<Guid> lstGuidId = new List<Guid>();
                    foreach (var item in get.DangerousGoodItems)
                    {
                        lstGuidId.Add((Guid)item.DangerousGoodItemId);
                    }

                    foreach (var id in lstGuidId)
                    {
                        DeleteDangerousGoodItem(id);
                    }
                }

                eManifestModel.DangerousGoods.DeleteObject(get);
            }
        }

        private void DeleteDangerousGoodItem_Sub(Guid dangerousGoodItemId)
        {
            var get = GetDangerousGoodItemModelById(dangerousGoodItemId);
            if (get != null)
                eManifestModel.DangerousGoodItems.DeleteObject(get);
        }

        /// <summary>
        /// Save DangerousGood object
        /// </summary>
        /// <param name="dangerousGoodDto"></param>
        /// <returns></returns>
        private void SaveDangerousGood_Sub(DangerousGoodDto dangerousGoodDto)
        {
            // Check document submited
            dangerousGoodDto.IsTemp = IsSubmitDocument(dangerousGoodDto.DocumentId);

            // Update document status
            if (dangerousGoodDto.IsTemp)
            {
                SetDocumentStatusUpdate(dangerousGoodDto.DocumentId, enumDocumentUpdate.DangerousGood);
            }

            var get = GetDangerousGoodModelByDocumentId(dangerousGoodDto.DocumentId, dangerousGoodDto.CreaterId, dangerousGoodDto.IsTemp);

            if (get != null)
            {
                // Update
                // get.DangerousGoodId = dangerousGoodDto.DangerousGoodId;
                get.PortOfLoad = dangerousGoodDto.PortOfLoad;
                get.PortOfUnload = dangerousGoodDto.PortOfUnload;
                get.ContNumber = dangerousGoodDto.ContNumber;
                get.ContSealNumber = dangerousGoodDto.ContSealNumber;
                get.ItemStatus = dangerousGoodDto.ItemStatus;
                get.CreaterId = dangerousGoodDto.CreaterId;
                get.DocumentId = dangerousGoodDto.DocumentId;
                get.ModifyId = dangerousGoodDto.ModifyId;
                get.IsTemp = dangerousGoodDto.IsTemp;

                // Save DangerousGoodItems
                foreach (var item in dangerousGoodDto.DangerousGoodItems)
                {
                    item.DangerousGoodId = get.DangerousGoodId;
                }

                SaveDangerousGoodItems(dangerousGoodDto.DangerousGoodItems);
            }
            else
            {
                // Insert
                get = ConvertDangerousGoodDtoToModel(dangerousGoodDto);

                // Add and Update
                foreach (var item in dangerousGoodDto.DangerousGoodItems)
                {
                    get.DangerousGoodItems.Add(ConvertDangerousGoodItemDtoToModel(item));
                }

                eManifestModel.DangerousGoods.AddObject(get);
            }
        }

        /// <summary>
        /// Delete object by documentId
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        private void DeleteDangerousGoodByDocumentId_Sub(Guid documentId, Guid createrId, bool isTemp)
        {
            var get = (from o in eManifestModel.DangerousGoods
                       where o.DocumentId == documentId && o.IsTemp == isTemp && (createrId == Guid.Empty ? true : o.CreaterId == createrId)
                       select o);

            if (get == null) return;

            List<Guid> lstGuidId = new List<Guid>();
            foreach (var item in get)
            {
                lstGuidId.Add(item.DangerousGoodId);
            }

            foreach (var id in lstGuidId)
            {
                DeleteDangerousGood_Sub(id);
            }
        }

        /// <summary>
        /// Delete object by document Id
        /// </summary>
        /// <param name="documentId"></param>
        /// <returns></returns>
        private void DeleteDangerousGoodByDocumentId_Sub(Guid documentId)
        {
            var get = (from o in eManifestModel.DangerousGoods
                       where o.DocumentId == documentId
                       select o).ToList();

            if (get != null)
            {
                foreach (var item in get)
                {
                    DeleteDangerousGood_Sub(item.DangerousGoodId);
                }
            }
        }

        /// <summary>
        /// Delete object by documentId
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        public ResponseDto DeleteDangerousGoodById(Guid itemId)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                DeleteDangerousGood_Sub(itemId);

                // Save change
                eManifestModel.SaveChanges();
            }

            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Delete object by documentId and userId
        /// </summary>
        /// <param name="documentId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public ResponseDto DeleteDangerousGoodByDocumentId(Guid documentId, Guid userId)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            eManifestModel.DeleteDangerousGood(documentId, userId);

            return ret;
        }

        /// <summary>
        /// Get list DangerousGoods by DangerousGood name
        /// </summary>
        /// <returns></returns>
        public List<DangerousGoodDto> GetListDangerousGood(Guid documentId, bool isTemp = false)
        {
            var lstret = new List<DangerousGoodDto>();

            var get = (from o in eManifestModel.DangerousGoods
                       where o.DocumentId == documentId && o.IsTemp == isTemp
                       select o);

            if (get != null)
            {
                foreach (var item in get)
                {
                    lstret.Add(ConvertDangerousGoodModelToDto(item));
                }
            }

            return lstret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        public DangerousGoodDto GetDangerousGoodById(Guid id)
        {
            DangerousGoodDto ret = null;

            var get = GetDangerousGoodModelById(id);

            if (get != null)
            {
                ret = ConvertDangerousGoodModelToDto(get);
            }

            return ret;
        }

        /// <summary>
        /// GetDangerousByDocumentId
        /// </summary>
        /// <param name="documentId"></param>
        /// <returns></returns>
        public DangerousGoodDto GetDangerousGoodByDocumentId(Guid documentId, Guid userId)
        {
            DangerousGoodDto ret = null;

            // Get from temp
            var get = (from o in eManifestModel.DangerousGoods
                       where o.DocumentId == documentId && o.CreaterId == userId && o.IsTemp == true
                       select o).FirstOrDefault() as DangerousGood;

            if (get != null)
            {
                if (get.DangerousGoodItems.Count > 0)
                {
                    ret = ConvertDangerousGoodModelToDto(get);
                    return ret;
                }
            }

            // Get from submited
            get = (from o in eManifestModel.DangerousGoods
                   where o.DocumentId == documentId && o.CreaterId == userId && o.IsTemp == false
                   select o).FirstOrDefault() as DangerousGood;

            if (get != null)
            {
                if (get.DangerousGoodItems.Count > 0)
                {
                    ret = ConvertDangerousGoodModelToDto(get);
                }
            }

            return ret;
        }

        /// <summary>
        /// Save DangerousGood object
        /// </summary>
        /// <param name="dangerousGoodDto"></param>
        /// <returns></returns>
        
        public ResponseDto SaveDangerousGood(DangerousGoodDto dangerousGoodDto)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                // Save
                SaveDangerousGood_Sub(dangerousGoodDto);

                // Save change
                eManifestModel.SaveChanges();
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }
        //save 1 record
       

        /// <summary>
        /// Delete object by Id
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        public ResponseDto DeleteDangerousGoodItemById(Guid itemId)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                DeleteDangerousGoodItem_Sub(itemId);

                // Save change
                eManifestModel.SaveChanges();
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        #region DangerousGoodItem

        /// <summary>
        /// Convert from model object to dto object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private DangerousGoodItemDto ConvertDangerousGoodItemModelToDto(DangerousGoodItem obj)
        {
            var ret = new DangerousGoodItemDto
            {
                DangerousGoodItemId = obj.DangerousGoodItemId,
                DangerousGoodId = obj.DangerousGoodId,
                RefNumber = obj.RefNumber,
                NumberContainer = obj.NumberContainer,
                NumberOfPackage = obj.NumberOfPackage,
                ProperShipping = obj.ProperShipping,
                GoodClass = obj.GoodClass,
                UNNumber = obj.UNNumber,
                PackingGroup = obj.PackingGroup,
                SubsidiaryRisk = obj.SubsidiaryRisk,
                FlashPoint = obj.FlashPoint,
                MarinePollutant = obj.MarinePollutant,
                GrossWeight = obj.GrossWeight,
                StowagePosition = obj.StowagePosition,
                ItemStatus = obj.ItemStatus
            };

            return ret;
        }

        /// <summary>
        /// Convert from dto object to model object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private DangerousGoodItem ConvertDangerousGoodItemDtoToModel(DangerousGoodItemDto obj)
        {
            var ret = new DangerousGoodItem
            {
                DangerousGoodItemId = obj.DangerousGoodItemId,
                DangerousGoodId = obj.DangerousGoodId,
                RefNumber = obj.RefNumber,
                NumberContainer = obj.NumberContainer,
                NumberOfPackage = obj.NumberOfPackage,
                ProperShipping = obj.ProperShipping,
                GoodClass = obj.GoodClass,
                UNNumber = obj.UNNumber,
                PackingGroup = obj.PackingGroup,
                SubsidiaryRisk = obj.SubsidiaryRisk,
                FlashPoint = obj.FlashPoint,
                MarinePollutant = obj.MarinePollutant,
                GrossWeight = obj.GrossWeight,
                StowagePosition = obj.StowagePosition,
                ItemStatus = obj.ItemStatus
            };

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        private DangerousGoodItem GetDangerousGoodItemModelById(Guid id)
        {
            var ret = (from o in eManifestModel.DangerousGoodItems
                       where o.DangerousGoodItemId == id
                       select o).FirstOrDefault() as DangerousGoodItem;

            return ret;
        }

        /// <summary>
        /// Save DangerousGoodItem object
        /// </summary>
        /// <param name="dangerousGoodItemDto"></param>
        /// <returns></returns>
        private ResponseDto SaveDangerousGoodItem_Sub(DangerousGoodItemDto dangerousGoodItemDto)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                var get = GetDangerousGoodItemModelById(dangerousGoodItemDto.DangerousGoodItemId);

                if (get != null)
                {
                    // Update
                    get.DangerousGoodItemId = dangerousGoodItemDto.DangerousGoodItemId;
                    get.DangerousGoodId = dangerousGoodItemDto.DangerousGoodId;
                    get.RefNumber = dangerousGoodItemDto.RefNumber;
                    get.NumberContainer = dangerousGoodItemDto.NumberContainer;
                    get.NumberOfPackage = dangerousGoodItemDto.NumberOfPackage;
                    get.ProperShipping = dangerousGoodItemDto.ProperShipping;
                    get.GoodClass = dangerousGoodItemDto.GoodClass;
                    get.UNNumber = dangerousGoodItemDto.UNNumber;
                    get.PackingGroup = dangerousGoodItemDto.PackingGroup;
                    get.SubsidiaryRisk = dangerousGoodItemDto.SubsidiaryRisk;
                    get.FlashPoint = dangerousGoodItemDto.FlashPoint;
                    get.MarinePollutant = dangerousGoodItemDto.MarinePollutant;
                    get.GrossWeight = dangerousGoodItemDto.GrossWeight;
                    get.StowagePosition = dangerousGoodItemDto.StowagePosition;
                    get.ItemStatus = dangerousGoodItemDto.ItemStatus;
                }
                else
                {
                    // Insert
                    get = ConvertDangerousGoodItemDtoToModel(dangerousGoodItemDto);
                    eManifestModel.DangerousGoodItems.AddObject(get);
                }
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Delete object by Id
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        private ResponseDto DeleteDangerousGoodItem(Guid id)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                var get = GetDangerousGoodItemModelById(id);

                if (get != null)
                {
                    eManifestModel.DangerousGoodItems.DeleteObject(get);
                }
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Save list DangerousGoodItemDto
        /// </summary>
        /// <param name="dangerousGoodItemDtos"></param>
        /// <returns></returns>
        private ResponseDto SaveDangerousGoodItems(List<DangerousGoodItemDto> dangerousGoodItemDtos)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            if (dangerousGoodItemDtos.Count == 0) return ret;
            Guid? DangerousGoodId = dangerousGoodItemDtos[0].DangerousGoodId;
            var get = (from o in eManifestModel.DangerousGoodItems
                       where o.DangerousGoodId == DangerousGoodId
                       select o).ToList();

            try
            {
                // Delete
                if (get != null)
                {
                    foreach (var item in get)
                    {
                        var search = (from o in dangerousGoodItemDtos
                                      where o.DangerousGoodItemId == item.DangerousGoodItemId
                                      select o).FirstOrDefault();

                        if (search == null)
                        {
                            DeleteDangerousGoodItem(item.DangerousGoodItemId);
                        }
                    }
                }

                // Add and Update
                foreach (var item in dangerousGoodItemDtos)
                {
                    SaveDangerousGoodItem_Sub(item);
                }
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }
        // Save 1 record
        private ResponseDto SaveDangerousGoodItemsRecord(DangerousGoodItemDto dangerousGoodItemDto)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            if (dangerousGoodItemDto == null) return ret;
            Guid? DangerousGoodId = dangerousGoodItemDto.DangerousGoodId;
            var get = (from o in eManifestModel.DangerousGoodItems
                       where o.DangerousGoodId == DangerousGoodId
                       select o).ToList();

            try
            {
                // Delete
                if (get != null)
                {
                    foreach (var item in get)
                    {
                        var search = (from o in eManifestModel.DangerousGoodItems
                                      where o.DangerousGoodItemId == item.DangerousGoodItemId
                                      select o).FirstOrDefault();

                        if (search == null)
                        {
                            DeleteDangerousGoodItem(item.DangerousGoodItemId);
                        }
                    }
                }

                // Add and Update
               
                    SaveDangerousGoodItem_Sub(dangerousGoodItemDto);
               
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        #endregion


        #endregion

        #region ShipStoreDeclaration

        /// <summary>
        /// Convert from model object to dto object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private ShipStoreDeclarationDto ConvertShipStoreDeclarationModelToDto(ShipStoreDeclaration obj, bool isAll = true)
        {
            var ret = new ShipStoreDeclarationDto
            {
                ShipStoreDeclarationId = obj.ShipStoreDeclarationId,
                PeriodOfStay = obj.PeriodOfStay,
                PlaceOfStorage = obj.PlaceOfStorage,
                CreaterId = obj.CreaterId,
                CreatedDate = obj.CreatedDate,
                ItemStatus = obj.ItemStatus,
                ModifyId = obj.ModifyId,
                IsTemp = obj.IsTemp,
                UploadType = enumUploadType.Original
            };

            // Dangerous Good Item
            if (isAll && obj.ShipStoreItems != null)
            {
                ret.ShipStoreItems = new List<ShipStoreItemDto>();
                foreach (var item in obj.ShipStoreItems)
                {
                    ret.ShipStoreItems.Add(ConvertShipStoreItemModelToDto(item));
                }
            }

            return ret;
        }

        /// <summary>
        /// Convert from dto object to model object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private ShipStoreDeclaration ConvertShipStoreDeclarationDtoToModel(ShipStoreDeclarationDto obj)
        {
            var ret = new ShipStoreDeclaration
            {
                ShipStoreDeclarationId = obj.ShipStoreDeclarationId,
                PeriodOfStay = obj.PeriodOfStay,
                PlaceOfStorage = obj.PlaceOfStorage,
                CreaterId = obj.CreaterId,
                CreatedDate = obj.CreatedDate,
                ItemStatus = obj.ItemStatus,
                DocumentId = obj.DocumentId,
                ModifyId = obj.ModifyId,
                IsTemp = obj.IsTemp,
            };

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        private ShipStoreDeclaration GetShipStoreDeclarationModelById(Guid id)
        {
            var ret = (from o in eManifestModel.ShipStoreDeclarations
                       where o.ShipStoreDeclarationId == id
                       select o).FirstOrDefault() as ShipStoreDeclaration;

            return ret;
        }

        /// <summary>
        /// Get object by document id and user id
        /// </summary>
        /// <returns></returns>
        private ShipStoreDeclaration GetShipStoreDeclarationModelByDocumentId(Guid documentId, Guid? userId, bool isTemp)
        {
            var ret = (from o in eManifestModel.ShipStoreDeclarations
                       where o.DocumentId == documentId && o.CreaterId == userId && o.IsTemp == isTemp
                       select o).FirstOrDefault() as ShipStoreDeclaration;

            return ret;
        }

        /// <summary>
        /// Delete object by documentId
        /// </summary>
        /// <param name="shipStoreId"></param>
        /// <returns></returns>
        private void DeleteShipStoreDeclaration_Sub(Guid shipStoreId)
        {
            var get = GetShipStoreDeclarationModelById(shipStoreId);

            if (get != null)
            {
                // Delete ship store items
                if (get.ShipStoreItems != null)
                {
                    List<Guid> lstGuidId = new List<Guid>();
                    foreach (var item in get.ShipStoreItems)
                    {
                        lstGuidId.Add(item.ShipStoreItemId);
                    }

                    foreach (var id in lstGuidId)
                    {
                        DeleteShipStoreItem(id);
                    }
                }

                eManifestModel.ShipStoreDeclarations.DeleteObject(get);
            }
        }

        /// <summary>
        /// Save ShipStoreDeclaration object
        /// </summary>
        /// <param name="shipStoreDeclarationDto"></param>
        /// <returns></returns>
        private void SaveShipStoreDeclaration_Sub(ShipStoreDeclarationDto shipStoreDeclarationDto)
        {
            shipStoreDeclarationDto.IsTemp = IsSubmitDocument(shipStoreDeclarationDto.DocumentId);

            // Update document status
            if (shipStoreDeclarationDto.IsTemp)
            {
                SetDocumentStatusUpdate(shipStoreDeclarationDto.DocumentId, enumDocumentUpdate.ShipStoreDeclaration);
            }

            var get = GetShipStoreDeclarationModelByDocumentId(shipStoreDeclarationDto.DocumentId, shipStoreDeclarationDto.CreaterId, shipStoreDeclarationDto.IsTemp);

            if (get != null)
            {
                // Update
                // get.ShipStoreDeclarationId = shipStoreDeclarationDto.ShipStoreDeclarationId;
                get.PeriodOfStay = shipStoreDeclarationDto.PeriodOfStay;
                get.PlaceOfStorage = shipStoreDeclarationDto.PlaceOfStorage;
                get.CreaterId = shipStoreDeclarationDto.CreaterId;
                get.CreatedDate = shipStoreDeclarationDto.CreatedDate;
                get.ItemStatus = shipStoreDeclarationDto.ItemStatus;
                get.DocumentId = shipStoreDeclarationDto.DocumentId;
                get.ModifyId = shipStoreDeclarationDto.ModifyId;
                get.IsTemp = shipStoreDeclarationDto.IsTemp;

                // Save list ship store item
                foreach (var item in shipStoreDeclarationDto.ShipStoreItems)
                {
                    item.ShipStoreDeclarationId = get.ShipStoreDeclarationId;
                }

                SaveShipStoreItems(shipStoreDeclarationDto.ShipStoreItems);
            }
            else
            {
                // Insert
                get = ConvertShipStoreDeclarationDtoToModel(shipStoreDeclarationDto);

                // Add and Update
                foreach (var item in shipStoreDeclarationDto.ShipStoreItems)
                {
                    get.ShipStoreItems.Add(ConvertShipStoreItemDtoToModel(item));
                }

                eManifestModel.ShipStoreDeclarations.AddObject(get);
            }
        }

        /// <summary>
        /// Delete object by document Id
        /// </summary>
        /// <param name="documentId"></param>
        /// <returns></returns>
        private void DeleteShipStoreDeclarationByDocumentId_Sub(Guid documentId)
        {
            var get = (from o in eManifestModel.ShipStoreDeclarations
                       where o.DocumentId == documentId
                       select o).ToList();

            if (get != null)
            {
                foreach (var item in get)
                {
                    DeleteShipStoreDeclaration_Sub(item.ShipStoreDeclarationId);
                }
            }
        }

        /// <summary>
        /// Delete object by documentId
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        private void DeleteShipStoreDeclarationByDocumentId_Sub(Guid documentId, Guid createrId, bool isTemp)
        {
            var get = (from o in eManifestModel.ShipStoreDeclarations
                       where o.DocumentId == documentId && o.IsTemp == isTemp && (createrId == Guid.Empty ? true : o.CreaterId == createrId)
                       select o);

            if (get == null) return;

            List<Guid> lstGuidId = new List<Guid>();
            foreach (var item in get)
            {
                lstGuidId.Add(item.ShipStoreDeclarationId);
            }

            foreach (var id in lstGuidId)
            {
                DeleteShipStoreDeclaration_Sub(id);
            }
        }

        /// <summary>
        /// Delete object by documentId
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        public ResponseDto DeleteShipStoreDeclarationByDocumentId(Guid documentId, bool isTemp = false)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                DeleteShipStoreDeclarationByDocumentId_Sub(documentId, Guid.Empty, isTemp);

                // Save change
                eManifestModel.SaveChanges();
            }

            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Delete object by documentId
        /// </summary>
        /// <param name="documentId"></param>
        /// <returns></returns>
        public ResponseDto DeleteShipStoreDeclarationByDocumentId(Guid documentId, Guid userId)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            eManifestModel.DeleteShipStoreDeclaration(documentId, userId);
            return ret;
        }

        /// <summary>
        /// Get list ShipStoreDeclarations by ShipStoreDeclaration name
        /// </summary>
        /// <returns></returns>
        public List<ShipStoreDeclarationDto> GetListShipStoreDeclaration(Guid documentId, bool isTemp = false)
        {
            var lstret = new List<ShipStoreDeclarationDto>();

            var get = (from o in eManifestModel.ShipStoreDeclarations
                       where o.DocumentId == documentId && o.IsTemp == isTemp
                       select o);

            if (get != null)
            {
                foreach (var item in get)
                {
                    lstret.Add(ConvertShipStoreDeclarationModelToDto(item));
                }
            }

            return lstret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        public ShipStoreDeclarationDto GetShipStoreDeclarationById(Guid id)
        {
            ShipStoreDeclarationDto ret = null;

            var get = GetShipStoreDeclarationModelById(id);

            if (get != null)
            {
                ret = ConvertShipStoreDeclarationModelToDto(get);
            }

            return ret;
        }

        /// <summary>
        /// GetShipStoreDeclarationByDocumentId 
        /// </summary>
        /// <param name="documentId"></param>
        /// <returns></returns>
        public ShipStoreDeclarationDto GetShipStoreDeclarationByDocumentId(Guid documentId, Guid userId)
        {
            ShipStoreDeclarationDto ret = null;

            // Get from temp
            var get = (from o in eManifestModel.ShipStoreDeclarations
                       where o.DocumentId == documentId && o.CreaterId == userId && o.IsTemp == true
                       select o).FirstOrDefault() as ShipStoreDeclaration;

            if (get != null)
            {
                if (get.ShipStoreItems.Count > 0)
                {
                    ret = ConvertShipStoreDeclarationModelToDto(get);
                    return ret;
                }
            }

            // Get from submited
            get = (from o in eManifestModel.ShipStoreDeclarations
                   where o.DocumentId == documentId && o.CreaterId == userId && o.IsTemp == false
                   select o).FirstOrDefault() as ShipStoreDeclaration;

            if (get != null)
            {
                ret = ConvertShipStoreDeclarationModelToDto(get);
            }

            return ret;
        }

        /// <summary>
        /// Save ShipStoreDeclaration object
        /// </summary>
        /// <param name="shipStoreDeclarationDto"></param>
        /// <returns></returns>
        public ResponseDto SaveShipStoreDeclaration(ShipStoreDeclarationDto shipStoreDeclarationDto)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                // Save
                SaveShipStoreDeclaration_Sub(shipStoreDeclarationDto);

                // Save change
                eManifestModel.SaveChanges();

            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }
        //Save 1 record
       
        /// <summary>
        /// Delete object by documentId
        /// </summary>
        /// <param name="documentId"></param>
        /// <returns></returns>
        public ResponseDto DeleteShipStoreDeclaration(Guid documentId)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                DeleteShipStoreDeclaration_Sub(documentId);

                // Save change
                eManifestModel.SaveChanges();
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        #region ShipStoreItem

        /// <summary>
        /// Convert from model object to dto object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private ShipStoreItemDto ConvertShipStoreItemModelToDto(ShipStoreItem obj)
        {
            var ret = new ShipStoreItemDto
            {
                ShipStoreItemId = obj.ShipStoreItemId,
                Name = obj.Name,
                Quantity = obj.Quantity,
                ItemStatus = obj.ItemStatus,
                ShipStoreDeclarationId = obj.ShipStoreDeclarationId
            };

            return ret;
        }

        /// <summary>
        /// Convert from dto object to model object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private ShipStoreItem ConvertShipStoreItemDtoToModel(ShipStoreItemDto obj)
        {
            var ret = new ShipStoreItem
            {
                ShipStoreItemId = obj.ShipStoreItemId,
                Name = obj.Name,
                Quantity = obj.Quantity,
                ItemStatus = obj.ItemStatus,
                ShipStoreDeclarationId = obj.ShipStoreDeclarationId
            };

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        private ShipStoreItem GetShipStoreItemModelById(Guid id)
        {
            var ret = (from o in eManifestModel.ShipStoreItems
                       where o.ShipStoreItemId == id
                       select o).FirstOrDefault() as ShipStoreItem;

            return ret;
        }

        /// <summary>
        /// Save ShipStoreItem object
        /// </summary>
        /// <param name="shipStoreItemDto"></param>
        /// <returns></returns>
        private ResponseDto SaveShipStoreItem_Sub(ShipStoreItemDto shipStoreItemDto)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                var get = GetShipStoreItemModelById(shipStoreItemDto.ShipStoreItemId);

                if (get != null)
                {
                    // Update
                    get.ShipStoreItemId = shipStoreItemDto.ShipStoreItemId;
                    get.Name = shipStoreItemDto.Name;
                    get.Quantity = shipStoreItemDto.Quantity;
                    get.ItemStatus = shipStoreItemDto.ItemStatus;
                    get.ShipStoreDeclarationId = shipStoreItemDto.ShipStoreDeclarationId;
                }
                else
                {
                    // Insert
                    get = ConvertShipStoreItemDtoToModel(shipStoreItemDto);
                    eManifestModel.ShipStoreItems.AddObject(get);
                }
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Delete object by Id
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        public ResponseDto DeleteShipStoreItem(Guid id)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                var get = GetShipStoreItemModelById(id);

                if (get != null)
                {
                    eManifestModel.ShipStoreItems.DeleteObject(get);
                }
                eManifestModel.SaveChanges();
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Save list ShipStoreItemDto
        /// </summary>
        /// <param name="shipStoreItemDtos"></param>
        /// <returns></returns>
        private ResponseDto SaveShipStoreItems(List<ShipStoreItemDto> shipStoreItemDtos)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            if (shipStoreItemDtos.Count == 0) return ret;
            Guid? ShipStoreDeclarationId = shipStoreItemDtos[0].ShipStoreDeclarationId;
            var get = (from o in eManifestModel.ShipStoreItems
                       where o.ShipStoreDeclarationId == ShipStoreDeclarationId
                       select o).ToList();

            try
            {
                // Delete
                if (get != null)
                {
                    foreach (var item in get)
                    {
                        var search = (from o in shipStoreItemDtos
                                      where o.ShipStoreItemId == item.ShipStoreItemId
                                      select o).FirstOrDefault();

                        if (search == null)
                        {
                            DeleteShipStoreItem(item.ShipStoreItemId);
                        }
                    }
                }

                // Add and Update
                foreach (var item in shipStoreItemDtos)
                {
                    SaveShipStoreItem_Sub(item);
                }
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        #endregion




        #endregion

        #region GoodDeclaration

        /// <summary>
        /// Convert from model object to dto object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private GoodDeclarationDto ConvertGoodDeclarationModelToDto(GoodDeclaration obj, bool isAll = true)
        {
            var ret = new GoodDeclarationDto
            {
                GoodDeclarationId = obj.GoodDeclarationId,
                DocumentId = obj.DocumentId,
                Decription = obj.Decription,
                NumberOfPackage = obj.NumberOfPackage,
                KindOfPackages = obj.KindOfPackages,
                CreaterId = obj.CreaterId,
                CreatedDate = obj.CreatedDate,
                ItemStatus = obj.ItemStatus,
                ModifyId = obj.ModifyId,
                IsTemp = obj.IsTemp,
                UploadType = enumUploadType.Original
            };

            // Dangerous Good Item
            if (isAll && obj.GoodItems != null)
            {
                ret.GoodItems = new List<GoodItemDto>();
                foreach (var item in obj.GoodItems)
                {
                    ret.GoodItems.Add(ConvertGoodItemModelToDto(item));
                }
            }

            return ret;
        }

        /// <summary>
        /// Convert from dto object to model object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private GoodDeclaration ConvertGoodDeclarationDtoToModel(GoodDeclarationDto obj)
        {
            var ret = new GoodDeclaration
            {
                GoodDeclarationId = obj.GoodDeclarationId,
                Decription = obj.Decription,
                NumberOfPackage = obj.NumberOfPackage,
                KindOfPackages = obj.KindOfPackages,
                CreaterId = obj.CreaterId,
                CreatedDate = obj.CreatedDate,
                ItemStatus = obj.ItemStatus,
                DocumentId = obj.DocumentId,
                ModifyId = obj.ModifyId,
                IsTemp = obj.IsTemp,
            };

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        private GoodDeclaration GetGoodDeclarationModelById(Guid id)
        {
            var ret = (from o in eManifestModel.GoodDeclarations
                       where o.GoodDeclarationId == id
                       select o).FirstOrDefault() as GoodDeclaration;

            return ret;
        }

        /// <summary>
        /// Get object by document id and user id
        /// </summary>
        /// <returns></returns>
        private GoodDeclaration GetGoodDeclarationModelByDocumentId(Guid documentId, Guid? userId, bool isTemp)
        {
            var ret = (from o in eManifestModel.GoodDeclarations
                       where o.DocumentId == documentId && o.CreaterId == userId && o.IsTemp == isTemp
                       select o).FirstOrDefault() as GoodDeclaration;

            return ret;
        }

        /// <summary>
        /// Delete object by documentId
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        private void DeleteGoodDeclaration_Sub(Guid goodId)
        {
            var get = GetGoodDeclarationModelById(goodId);

            if (get != null)
            {
                // Delete good items
                if (get.GoodItems != null)
                {
                    List<Guid> lstGuidId = new List<Guid>();
                    foreach (var item in get.GoodItems)
                    {
                        lstGuidId.Add(item.GoodItemId);
                    }

                    foreach (var id in lstGuidId)
                    {
                        DeleteGoodItem(id);
                    }
                }

                eManifestModel.GoodDeclarations.DeleteObject(get);
            }
        }

        /// <summary>
        /// Delete object by document Id
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        private void DeleteGoodDeclarationByDocumentId_Sub(Guid documentId)
        {
            var get = (from o in eManifestModel.GoodDeclarations
                       where o.DocumentId == documentId
                       select o).ToList();

            if (get != null)
            {
                foreach (var item in get)
                {
                    DeleteGoodDeclaration_Sub(item.GoodDeclarationId);
                }
            }
        }

        /// <summary>
        /// Save GoodDeclaration object
        /// </summary>
        /// <param name="goodDeclarationDto"></param>
        /// <returns></returns>
        private void SaveGoodDeclaration_Sub(GoodDeclarationDto goodDeclarationDto)
        {
            goodDeclarationDto.IsTemp = IsSubmitDocument(goodDeclarationDto.DocumentId);

            // Update document status
            if (goodDeclarationDto.IsTemp)
            {
                SetDocumentStatusUpdate(goodDeclarationDto.DocumentId, enumDocumentUpdate.GoodDeclaration);
            }

            var get = GetGoodDeclarationModelByDocumentId(goodDeclarationDto.DocumentId, goodDeclarationDto.CreaterId, goodDeclarationDto.IsTemp);

            if (get != null)
            {
                // Update
                // get.GoodDeclarationId = goodDeclarationDto.GoodDeclarationId;
                get.Decription = goodDeclarationDto.Decription;
                get.NumberOfPackage = goodDeclarationDto.NumberOfPackage;
                get.KindOfPackages = goodDeclarationDto.KindOfPackages;
                get.CreaterId = goodDeclarationDto.CreaterId;
                get.CreatedDate = goodDeclarationDto.CreatedDate;
                get.ItemStatus = goodDeclarationDto.ItemStatus;
                get.DocumentId = goodDeclarationDto.DocumentId;
                get.ModifyId = goodDeclarationDto.ModifyId;
                get.IsTemp = goodDeclarationDto.IsTemp;

                // Save list GoodItems
                foreach (var item in goodDeclarationDto.GoodItems)
                {
                    item.GoodDeclarationId = get.GoodDeclarationId;
                }

                SaveGoodItems(goodDeclarationDto.GoodItems);
            }
            else
            {
                // Insert
                get = ConvertGoodDeclarationDtoToModel(goodDeclarationDto);

                // Add and Update
                foreach (var item in goodDeclarationDto.GoodItems)
                {
                    get.GoodItems.Add(ConvertGoodItemDtoToModel(item));
                }

                eManifestModel.GoodDeclarations.AddObject(get);
            }
        }

        /// <summary>
        /// Delete object by documentId
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        private void DeleteGoodDeclarationByDocumentId_Sub(Guid documentId, Guid createrId, bool isTemp)
        {
            var get = (from o in eManifestModel.GoodDeclarations
                       where o.DocumentId == documentId && o.IsTemp == isTemp && (createrId == Guid.Empty ? true : o.CreaterId == createrId)
                       select o);

            if (get == null) return;

            List<Guid> lstGuidId = new List<Guid>();
            foreach (var item in get)
            {
                lstGuidId.Add(item.GoodDeclarationId);
            }

            foreach (var id in lstGuidId)
            {
                DeleteGoodDeclaration_Sub(id);
            }
        }

        /// <summary>
        /// Delete object by documentId
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        public ResponseDto DeleteGoodDeclarationByDocumentId(Guid documentId, bool isTemp = true)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                DeleteGoodDeclarationByDocumentId_Sub(documentId, Guid.Empty, isTemp);

                // Save change
                eManifestModel.SaveChanges();
            }

            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Get list GoodDeclarations by GoodDeclaration name
        /// </summary>
        /// <returns></returns>
        public List<GoodDeclarationDto> GetListGoodDeclaration(Guid documentId, bool isTemp = true)
        {
            var lstret = new List<GoodDeclarationDto>();

            var get = (from o in eManifestModel.GoodDeclarations
                       where o.DocumentId == documentId && o.IsTemp == isTemp
                       select o);

            if (get != null)
            {
                foreach (var item in get)
                {
                    lstret.Add(ConvertGoodDeclarationModelToDto(item));
                }
            }

            return lstret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        public GoodDeclarationDto GetGoodDeclarationById(Guid id)
        {
            GoodDeclarationDto ret = null;

            var get = GetGoodDeclarationModelById(id);

            if (get != null)
            {
                ret = ConvertGoodDeclarationModelToDto(get);
            }

            return ret;
        }

        /// <summary>
        /// GetGoodDeclarationByDocumentId
        /// </summary>
        /// <param name="documentId"></param>
        /// <returns></returns>
        public GoodDeclarationDto GetGoodDeclarationByDocumentId(Guid documentId, Guid userId)
        {
            GoodDeclarationDto ret = null;

            // get from temp
            var get = (from o in eManifestModel.GoodDeclarations
                       where o.DocumentId == documentId && o.CreaterId == userId && o.IsTemp == true
                       select o).FirstOrDefault() as GoodDeclaration;

            if (get != null)
            {
                if (get.GoodItems.Count > 0)
                {
                    ret = ConvertGoodDeclarationModelToDto(get, false);
                    return ret;
                }
            }

            // Get from submit
            get = (from o in eManifestModel.GoodDeclarations
                   where o.DocumentId == documentId && o.CreaterId == userId && o.IsTemp == false
                   select o).FirstOrDefault() as GoodDeclaration;

            if (get != null)
            {
                if (get.GoodItems.Count > 0)
                {
                    ret = ConvertGoodDeclarationModelToDto(get, false);
                }
            }

            return ret;
        }

        /// <summary>
        /// Save GoodDeclaration object
        /// </summary>
        /// <param name="goodDeclarationDto"></param>
        /// <returns></returns>
        public ResponseDto SaveGoodDeclaration(GoodDeclarationDto goodDeclarationDto, bool isTemp = true)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                // Save 
                SaveGoodDeclaration_Sub(goodDeclarationDto);

                // Save change
                eManifestModel.SaveChanges();

            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Delete object by documentId
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        public ResponseDto DeleteGoodDeclaration(Guid id, bool isTemp = true)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                DeleteGoodDeclaration_Sub(id);

                // Save change
                eManifestModel.SaveChanges();
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }


        /// <summary>
        /// Delete object by documentId
        /// </summary>
        /// <param name="documentId"></param>
        /// <returns></returns>
        public ResponseDto DeleteGoodDeclarationByDocumentId(Guid documentId, Guid userId)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            eManifestModel.DeleteGoodDeclaration(documentId, userId);
            //try
            //{
            //    bool isTemp;
            //    Guid ownerId;
            //    GetDocument(documentId, out isTemp, out ownerId);
            //    userId = ownerId == userId ? Guid.Empty : userId;

            //    DeleteGoodDeclarationByDocumentId_Sub(documentId, userId, isTemp);

            //    // Save change
            //    eManifestModel.SaveChanges();
            //}

            //catch (Exception ex)
            //{
            //    ret.IsSuccess = false;
            //    ret.ErroeMessage = ex.Message;
            //}

            return ret;
        }


        #region GoodItem

        /// <summary>
        /// Convert from model object to dto object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private GoodItemDto ConvertGoodItemModelToDto(GoodItem obj)
        {
            var ret = new GoodItemDto
            {
                GoodItemId = obj.GoodItemId,
                MasterBillNo = obj.MasterBillNo,
                Consigner = obj.Consigner,
                Consignee = obj.Consignee,
                NotificatedParty = obj.NotificatedParty,
                ContNumber = obj.ContNumber,
                ContSealNumber = obj.ContSealNumber,
                GoodDescription = obj.GoodDescription,
                NetWeight = obj.NetWeight,
                GrossWeight = obj.GrossWeight,
                Demension = obj.Demension,
                RefNumber = obj.RefNumber,
                Ajustment = obj.Ajustment,
                ItemStatus = obj.ItemStatus,
                GoodDeclarationId = obj.GoodDeclarationId,
                ItemCodeId = obj.ItemCodeId
            };

            // Item code
            if (obj.ItemCode != null)
            {
                ret.ItemCode = ConvertItemCodeModelToDto(obj.ItemCode);
            }

            return ret;
        }

        /// <summary>
        /// Convert from dto object to model object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private GoodItem ConvertGoodItemDtoToModel(GoodItemDto obj)
        {
            var ret = new GoodItem
            {
                GoodItemId = obj.GoodItemId,
                MasterBillNo = obj.MasterBillNo,
                Consigner = obj.Consigner,
                Consignee = obj.Consignee,
                NotificatedParty = obj.NotificatedParty,
                ContNumber = obj.ContNumber,
                ContSealNumber = obj.ContSealNumber,
                GoodDescription = obj.GoodDescription,
                NetWeight = obj.NetWeight,
                GrossWeight = obj.GrossWeight,
                Demension = obj.Demension,
                RefNumber = obj.RefNumber,
                Ajustment = obj.Ajustment,
                ItemStatus = obj.ItemStatus,
                GoodDeclarationId = obj.GoodDeclarationId,
                ItemCodeId = obj.ItemCodeId
            };

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        private GoodItem GetGoodItemModelById(Guid id)
        {
            var ret = (from o in eManifestModel.GoodItems
                       where o.GoodItemId == id
                       select o).FirstOrDefault() as GoodItem;

            return ret;
        }

        /// <summary>
        /// Save GoodItem object
        /// </summary>
        /// <param name="goodItemDto"></param>
        /// <returns></returns>
        private ResponseDto SaveGoodItem_Sub(GoodItemDto goodItemDto)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                var get = GetGoodItemModelById(goodItemDto.GoodItemId);

                if (get != null)
                {
                    // Update
                    get.GoodItemId = goodItemDto.GoodItemId;
                    get.MasterBillNo = goodItemDto.MasterBillNo;
                    get.Consigner = goodItemDto.Consigner;
                    get.Consignee = goodItemDto.Consignee;
                    get.NotificatedParty = goodItemDto.NotificatedParty;
                    get.ContNumber = goodItemDto.ContNumber;
                    get.ContSealNumber = goodItemDto.ContSealNumber;
                    get.GoodDescription = goodItemDto.GoodDescription;
                    get.NetWeight = goodItemDto.NetWeight;
                    get.GrossWeight = goodItemDto.GrossWeight;
                    get.Demension = goodItemDto.Demension;
                    get.RefNumber = goodItemDto.RefNumber;
                    get.Ajustment = goodItemDto.Ajustment;
                    get.ItemStatus = goodItemDto.ItemStatus;
                    get.GoodDeclarationId = goodItemDto.GoodDeclarationId;
                    get.ItemCodeId = goodItemDto.ItemCodeId;
                }
                else
                {
                    // Insert
                    get = ConvertGoodItemDtoToModel(goodItemDto);
                    eManifestModel.GoodItems.AddObject(get);
                }
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Delete object by Id
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        public ResponseDto DeleteGoodItem(Guid id)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                var get = GetGoodItemModelById(id);

                if (get != null)
                {
                    eManifestModel.GoodItems.DeleteObject(get);
                }
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Save list GoodItemDto
        /// </summary>
        /// <param name="goodItemDtos"></param>
        /// <returns></returns>
        private ResponseDto SaveGoodItems(List<GoodItemDto> goodItemDtos)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            if (goodItemDtos.Count == 0) return ret;
            Guid? GoodDeclarationId = goodItemDtos[0].GoodDeclarationId;
            var get = (from o in eManifestModel.GoodItems
                       where o.GoodDeclarationId == GoodDeclarationId
                       select o).ToList();

            try
            {
                // Delete
                if (get != null)
                {
                    foreach (var item in get)
                    {
                        var search = (from o in goodItemDtos
                                      where o.GoodItemId == item.GoodItemId
                                      select o).FirstOrDefault();

                        if (search == null)
                        {
                            DeleteGoodItem(item.GoodItemId);
                        }
                    }
                }

                // Add and Update
                foreach (var item in goodItemDtos)
                {
                    SaveGoodItem_Sub(item);
                }
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        #endregion


        #endregion

        #region HouseBill

        /// <summary>
        /// Convert from model object to dto object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private HouseBillDto ConvertHouseBillModelToDto(HouseBill obj, bool isAll = true)
        {
            var ret = new HouseBillDto
            {
                HouseBillId = obj.HouseBillId,
                DocumentId = obj.DocumentId,
                Consigner = obj.Consigner,
                Consignee = obj.Consignee,
                PortIdOfTranship = obj.PortOfTranship,
                PortIdOfDestination = obj.PortOfDestination,
                PortIdOfLoad = obj.PortOfLoad,
                PortIdOfUnload = obj.PortOfUnload,
                PortNameOfTranship = obj.PortNameOfTranship,
                PortNameOfDestination = obj.PortNameOfDestination,
                PortNameOfLoad = obj.PortNameOfLoad,
                PortNameOfUnload = obj.PortNameOfUnload,
                BillNumber = obj.BillNumber.Trim(),
                DateOfBill = obj.DateOfBill,
                MasterBillNo = obj.MasterBillNo.Trim(),
                DateOfMasterBill = obj.DateOfMasterBill,
                NumberOfPackage = obj.NumberOfPackage,
                KindOfPackages = obj.KindOfPackages,
                DepartureDate = obj.DepartureDate,
                CreaterId = obj.CreaterId,
                CreatedDate = obj.CreatedDate,
                ItemStatus = obj.ItemStatus,
                IsTemp = obj.IsTemp,

            };


            return ret;
        }

        /// <summary>
        /// Convert from dto object to model object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private HouseBill ConvertHouseBillDtoToModel(HouseBillDto obj)
        {
            var ret = new HouseBill
            {
                HouseBillId = obj.HouseBillId,
                DocumentId = obj.DocumentId,
                Consigner = obj.Consigner,
                Consignee = obj.Consignee,
                PortOfTranship = obj.PortIdOfTranship,
                PortOfDestination = obj.PortIdOfDestination,
                PortOfLoad = obj.PortIdOfLoad,
                PortOfUnload = obj.PortIdOfUnload,
                PortNameOfTranship = obj.PortNameOfTranship,
                PortNameOfDestination = obj.PortNameOfDestination,
                PortNameOfLoad = obj.PortNameOfLoad,
                PortNameOfUnload = obj.PortNameOfUnload,
                BillNumber = obj.BillNumber,
                DateOfBill = obj.DateOfBill,
                MasterBillNo = obj.MasterBillNo,
                DateOfMasterBill = obj.DateOfMasterBill,
                DepartureDate = obj.DepartureDate,
                NumberOfPackage = obj.NumberOfPackage,
                KindOfPackages = obj.KindOfPackages,
                CreaterId = obj.CreaterId,
                CreatedDate = obj.CreatedDate,
                ItemStatus = obj.ItemStatus,
                IsTemp = obj.IsTemp,
            };

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        private HouseBill GetHouseBillModelById(Guid id)
        {
            var ret = (from o in eManifestModel.HouseBills
                       where o.HouseBillId == id
                       select o).FirstOrDefault() as HouseBill;

            return ret;
        }

        ///// <summary>
        ///// Get object by document id and user id
        ///// </summary>
        ///// <returns></returns>
        //public List<HouseBill> GetHouseBillModelByDocumentId(Guid documentId, Guid userId, bool isTemp)
        //{
        //    var ret = (from o in eManifestModel.HouseBills
        //               where o.DocumentId == documentId && o.CreaterId == userId && o.IsTemp == isTemp
        //               select o).ToList() as List<HouseBill>;

        //    return ret;
        //}
        /// <summary>
        /// Get object by document id and user id
        /// </summary>
        /// <returns></returns>
        public HouseBill GetHouseBillModelByDocumentId(Guid documentId, Guid userId, bool isTemp)
        {
            //var ret = (from o in eManifestModel.HouseBills
            //           where o.DocumentId == documentId && o.CreaterId == userId && o.IsTemp == isTemp
            //           select o).FirstOrDefault() as HouseBill;
            var ret = eManifestModel.HouseBills.Where(i => i.DocumentId == documentId).FirstOrDefault() as HouseBill;
            return ret;
        }

        /// <summary>
        /// Get object by document id and user id
        /// </summary>
        /// <returns></returns>
        public HouseBill GetHouseBillModelByHouseBillNo(Guid documentId, Guid userId, string houseBillNo, bool isTemp)
        {
            var ret = (from o in eManifestModel.HouseBills
                       where o.DocumentId == documentId && o.CreaterId == userId && houseBillNo.Trim().Equals(o.BillNumber.Trim()) && o.IsTemp == isTemp
                       select o).FirstOrDefault() as HouseBill;

            return ret;
        }

        /// <summary>
        /// Delete object by documentId
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        private void DeleteHouseBill_Sub(Guid Id)
        {
            var get = GetHouseBillModelById(Id);

            if (get != null)
            {
                // Delete good items
                if (get.HouseBillItems != null)
                {
                    List<Guid> lstGuidId = new List<Guid>();
                    foreach (var item in get.HouseBillItems)
                    {
                        lstGuidId.Add(item.HouseBillItemId);
                    }

                    foreach (var id in lstGuidId)
                    {
                        DeleteHouseBillItem(id);
                    }
                }

                eManifestModel.HouseBills.DeleteObject(get);
            }
        }

        /// <summary>
        /// Delete object by document Id
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        private void DeleteHouseBillByDocumentId_Sub(Guid documentId)
        {
            var get = (from o in eManifestModel.HouseBills
                       where o.DocumentId == documentId
                       select o).ToList();

            if (get != null)
            {
                foreach (var item in get)
                {
                    DeleteHouseBill_Sub(item.HouseBillId);
                }
            }
        }

        /// <summary>
        /// Delete object by documentId
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        private void DeleteHouseBillByDocumentId_Sub(Guid documentId, Guid createrId, bool isTemp)
        {
            var get = (from o in eManifestModel.HouseBills
                       where o.DocumentId == documentId && o.IsTemp == isTemp && (createrId == Guid.Empty ? true : o.CreaterId == createrId)
                       select o);

            if (get == null) return;

            List<Guid> lstGuidId = new List<Guid>();
            foreach (var item in get)
            {
                lstGuidId.Add(item.HouseBillId);
            }

            foreach (var id in lstGuidId)
            {
                DeleteHouseBill_Sub(id);
            }
        }

        /// <summary>
        /// Save HouseBill object
        /// </summary>
        /// <param name="houseBillDto"></param>
        /// <returns></returns>
        private void SaveHouseBill_Sub(HouseBillDto houseBillDto)
        {
            houseBillDto.IsTemp = IsSubmitDocument(houseBillDto.DocumentId);

            // Update document status
            if (houseBillDto.IsTemp)
            {
                SetDocumentStatusUpdate(houseBillDto.DocumentId, enumDocumentUpdate.HouseBill);
            }

            var get = GetHouseBillModelByDocumentId(houseBillDto.DocumentId, houseBillDto.CreaterId, houseBillDto.IsTemp);

            if (get != null)
            {
                // Update
                //get.HouseBillId = houseBillDto.HouseBillId;
                //get.DocumentId = houseBillDto.DocumentId;
                get.Consigner = houseBillDto.Consigner;
                get.Consignee = houseBillDto.Consignee;
                get.PortOfTranship = houseBillDto.PortIdOfTranship;
                get.PortOfDestination = houseBillDto.PortIdOfDestination;
                get.PortOfLoad = houseBillDto.PortIdOfLoad;
                get.PortOfUnload = houseBillDto.PortIdOfUnload;
                get.BillNumber = houseBillDto.BillNumber;
                get.DateOfBill = houseBillDto.DateOfBill;
                get.MasterBillNo = houseBillDto.MasterBillNo;
                get.DateOfMasterBill = houseBillDto.DateOfMasterBill;
                get.DepartureDate = houseBillDto.DepartureDate;
                //get.CreaterId = houseBillDto.CreaterId;
                //get.CreatedDate = houseBillDto.CreatedDate;
                get.ItemStatus = houseBillDto.ItemStatus;
                get.IsTemp = houseBillDto.IsTemp;


                get.PortNameOfTranship = houseBillDto.PortNameOfTranship;
                get.PortNameOfDestination = houseBillDto.PortNameOfDestination;
                get.PortNameOfLoad = houseBillDto.PortNameOfLoad;
                get.PortNameOfUnload = houseBillDto.PortNameOfUnload;

                // Save list GoodItems
                if (houseBillDto.HouseBillItems != null && houseBillDto.HouseBillItems.Count > 0)
                {
                    foreach (var item in houseBillDto.HouseBillItems)
                    {
                        item.HouseBillId = get.HouseBillId;
                    }

                    SaveHouseBillItems(houseBillDto.HouseBillItems);
                }
            }
            else
            {
                // Insert
                get = ConvertHouseBillDtoToModel(houseBillDto);

                // Add and Update
                foreach (var item in houseBillDto.HouseBillItems)
                {
                    get.HouseBillItems.Add(ConvertHouseBillItemDtoToModel(item));
                }

                eManifestModel.HouseBills.AddObject(get);
            }
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        public HouseBillDto GetHouseBillById(Guid id)
        {
            HouseBillDto ret = null;

            var get = GetHouseBillModelById(id);

            if (get != null)
            {
                ret = ConvertHouseBillModelToDto(get);
            }

            return ret;
        }

        /// <summary>
        /// GetHouseBillByDocumentId
        /// </summary>
        /// <param name="documentId"></param>
        /// <returns></returns>
        public List<HouseBillDto> GetHouseBillByDocumentId(Guid documentId, Guid userId)
        {
            List<HouseBillDto> ret = new List<HouseBillDto>();

            // get from temp
            var get = (from o in eManifestModel.HouseBills
                       where o.DocumentId == documentId && o.CreaterId == userId && o.IsTemp == true
                       select o).ToList();

            if (get != null)
            {
                foreach (var item in get)
                {
                    ret.Add(ConvertHouseBillModelToDto(item));
                    return ret;
                }
                //if (get.HouseBillItems.Count > 0)
                //{
                //    ret = ConvertHouseBillModelToDto(get);
                //    return ret;
                //}
            }

            // Get from submit
            get = (from o in eManifestModel.HouseBills
                   where o.DocumentId == documentId && o.CreaterId == userId && o.IsTemp == false
                   select o).ToList();

            if (get != null)
            {
                foreach (var item in get)
                {
                    ret.Add(ConvertHouseBillModelToDto(item));
                    return ret;
                }
                //if (get.HouseBillItems.Count > 0)
                //{
                //    ret = ConvertHouseBillModelToDto(get);
                //}
            }

            return ret;
        }

        /// <summary>
        /// Save HouseBill object
        /// </summary>
        /// <param name="houseBillDto"></param>
        /// <returns></returns>
        public ResponseDto SaveHouseBill(HouseBillDto houseBillDto)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                // Save 
                SaveHouseBill_Sub(houseBillDto);

                // Save change
                eManifestModel.SaveChanges();

            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Delete object by documentId
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        public ResponseDto DeleteHouseBill(Guid id)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                DeleteHouseBill_Sub(id);

                // Save change
                eManifestModel.SaveChanges();
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Delete object by documentId
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        public ResponseDto DeleteHouseBillByDocumentId(Guid documentId, Guid userId)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };
            bool isTemp = IsSubmitDocument(documentId);
            try
            {
                DeleteHouseBillByDocumentId_Sub(documentId, userId, isTemp);

                // Save change
                eManifestModel.SaveChanges();
            }

            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }


        #region HouseBillItem

        /// <summary>
        /// Convert from model object to dto object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private HouseBillItemDto ConvertHouseBillItemModelToDto(HouseBillItem obj)
        {
            var ret = new HouseBillItemDto
            {
                HouseBillItemId = obj.HouseBillItemId,
                HouseBillId = obj.HouseBillId,
                Description = obj.Description,
                GrossWeight = obj.GrossWeight,
                Demension = obj.Demension,
                ContNumber = obj.ContNumber,
                ContSealNumber = obj.ContSealNumber,
                ItemStatus = obj.ItemStatus,
                ItemCodeId = obj.ItemCodeId
            };

            // Item code
            if (obj.ItemCodeId != null)
            {
                //ret.ItemCode = ConvertItemCodeModelToDto(obj.ItemCode);
            }

            return ret;
        }

        /// <summary>
        /// Convert from dto object to model object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private HouseBillItem ConvertHouseBillItemDtoToModel(HouseBillItemDto obj)
        {
            var ret = new HouseBillItem
            {
                HouseBillItemId = obj.HouseBillItemId,
                HouseBillId = obj.HouseBillId,
                Description = obj.Description,
                GrossWeight = obj.GrossWeight,
                Demension = obj.Demension,
                ContNumber = obj.ContNumber,
                ContSealNumber = obj.ContSealNumber,
                ItemStatus = obj.ItemStatus,
                ItemCodeId = obj.ItemCodeId
            };

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        private HouseBillItem GetHouseBillItemModelById(Guid id)
        {
            var ret = (from o in eManifestModel.HouseBillItems
                       where o.HouseBillItemId == id
                       select o).FirstOrDefault() as HouseBillItem;

            return ret;
        }

        /// <summary>
        /// Save HouseBillItem object
        /// </summary>
        /// <param name="houseBillItem"></param>
        /// <returns></returns>
        public ResponseDto SaveHouseBillItem(HouseBillItemDto houseBillItem)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                var get = GetHouseBillItemModelById(houseBillItem.HouseBillItemId);

                if (get != null)
                {
                    // Update                   
                    //get.HouseBillId = houseBillItem.HouseBillId;
                    get.Description = houseBillItem.Description;
                    get.GrossWeight = houseBillItem.GrossWeight;
                    get.Demension = houseBillItem.Demension;
                    get.ContNumber = houseBillItem.ContNumber;
                    get.ContSealNumber = houseBillItem.ContSealNumber;
                    //get.ItemStatus = houseBillItem.ItemStatus;
                    //get.ItemCodeId = houseBillItem.ItemCodeId;
                }
                else
                {
                    // Insert
                    get = ConvertHouseBillItemDtoToModel(houseBillItem);
                    eManifestModel.HouseBillItems.AddObject(get);
                }

                // Save change
                eManifestModel.SaveChanges();
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Delete object by Id
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        public ResponseDto DeleteHouseBillItem(Guid id)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                var get = GetHouseBillItemModelById(id);

                if (get != null)
                {
                    eManifestModel.HouseBillItems.DeleteObject(get);
                }
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Save list HouseBillItemDto
        /// </summary>
        /// <param name="HouseBillItemDtos"></param>
        /// <returns></returns>
        private ResponseDto SaveHouseBillItems(List<HouseBillItemDto> HouseBillItemDtos)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            if (HouseBillItemDtos.Count == 0) return ret;

            Guid houseBillId = HouseBillItemDtos[0].HouseBillId;
            var get = (from o in eManifestModel.HouseBillItems
                       where o.HouseBillId == houseBillId
                       select o).ToList();

            try
            {
                // Delete
                if (get != null)
                {
                    foreach (var item in get)
                    {
                        var search = (from o in HouseBillItemDtos
                                      where o.HouseBillItemId == item.HouseBillItemId
                                      select o).FirstOrDefault();

                        if (search == null)
                        {
                            DeleteHouseBillItem(item.HouseBillItemId);
                        }
                    }
                }

                // Add and Update
                foreach (var item in HouseBillItemDtos)
                {
                    SaveHouseBillItem(item);
                }
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        #endregion


        #endregion

        #region Crew

        /// <summary>
        /// Convert from model object to dto object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private CrewDto ConvertCrewModelToDto(Crew obj)
        {
            var ret = new CrewDto
            {
                CrewId = obj.CrewId,
                DocumentId = obj.DocumentId,
                FamilyName = obj.FamilyName,
                GivenName = obj.GivenName,
                Rank = obj.Rank,
                StateId = obj.StateId,
                BirthDate = obj.BirthDate,
                BirthPlace = obj.BirthPlace,
                PassportType = obj.PassportType.Trim(),
                PassportNumber = obj.PassportNumber,
                PassportValidDate = obj.PassportValidDate,
                ItemStatus = obj.ItemStatus,
                CreaterId = obj.CreaterId,
                CreatedDate = obj.CreatedDate,
                ModifyId = obj.ModifyId,
                IsTemp = obj.IsTemp,
                UploadType = enumUploadType.Original
            };

            //// Passport type
            //if (obj.PassportType1 != null)
            //{
            //    ret.PassportTypeDto = ConvertPassportTypeModelToDto(obj.PassportType1);
            //}
            //// State
            //if (obj.State != null)
            //{
            //    ret.State = ConvertStateModelToDto(obj.State);
            //}

            return ret;
        }

        /// <summary>
        /// Convert from dto object to model object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private Crew ConvertCrewDtoToModel(CrewDto obj)
        {
            var ret = new Crew
            {
                CrewId = obj.CrewId,
                DocumentId = obj.DocumentId,
                FamilyName = obj.FamilyName,
                GivenName = obj.GivenName,
                Rank = obj.Rank,
                StateId = obj.StateId,
                BirthDate = obj.BirthDate,
                BirthPlace = obj.BirthPlace,
                PassportType = obj.PassportType,
                PassportNumber = obj.PassportNumber,
                PassportValidDate = obj.PassportValidDate,
                ItemStatus = obj.ItemStatus,
                CreaterId = obj.CreaterId,
                CreatedDate = obj.CreatedDate,
                ModifyId = obj.ModifyId,
                IsTemp = obj.IsTemp,
            };

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        private Crew GetCrewModelById(Guid id)
        {
            var ret = (from o in eManifestModel.Crews
                       where o.CrewId == id
                       select o).FirstOrDefault() as Crew;

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        public CrewDto GetCrewById(Guid id)
        {
            CrewDto ret = null;

            var get = GetCrewModelById(id);

            if (get != null)
            {
                ret = ConvertCrewModelToDto(get);
            }

            return ret;
        }

        /// <summary>
        /// Get list Crews by Crew name
        /// </summary>
        /// <returns></returns>
        public List<CrewDto> GetListCrew(Guid documentId, Guid userId)
        {
            var lstret = new List<CrewDto>();

            // Get from temp
            var get = (from o in eManifestModel.Crews
                       where o.DocumentId == documentId && o.CreaterId == userId && o.IsTemp == true
                       select o).ToList();

            if (get != null)
            {
                if (get.Count > 0)
                {
                    foreach (var item in get)
                    {
                        lstret.Add(ConvertCrewModelToDto(item));
                    }

                    return lstret;
                }
            }

            // Get form submited
            get = (from o in eManifestModel.Crews
                   where o.DocumentId == documentId && o.CreaterId == userId && o.IsTemp == false
                   select o).ToList();

            if (get != null)
            {
                if (get.Count > 0)
                {
                    foreach (var item in get)
                    {
                        lstret.Add(ConvertCrewModelToDto(item));
                    }
                }
            }

            return lstret;
        }

        /// <summary>
        /// Delete object by documentId
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        private void DeleteCrewByDocumentId_Sub(Guid documentId, Guid createrId, bool isTemp)
        {
            var get = (from o in eManifestModel.Crews
                       where o.DocumentId == documentId && o.IsTemp == isTemp && (createrId == Guid.Empty ? true : o.CreaterId == createrId)
                       select o);

            if (get == null) return;

            List<Guid> lstGuidId = new List<Guid>();
            foreach (var item in get)
            {
                lstGuidId.Add(item.CrewId);
            }

            foreach (var id in lstGuidId)
            {
                DeleteCrew_Sub(id);
            }
        }

        /// <summary>
        /// Delete object by document Id
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        private void DeleteCrewByDocumentId_Sub(Guid documentId)
        {
            var get = (from o in eManifestModel.Crews
                       where o.DocumentId == documentId
                       select o).ToList();

            if (get != null)
            {
                foreach (var item in get)
                {
                    DeleteCrew_Sub(item.CrewId);
                }
            }
        }

        /// <summary>
        /// Delete object by document Id
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        private void DeleteCrew_Sub(Guid id)
        {
            var get = GetCrewModelById(id);

            if (get != null)
            {
                eManifestModel.Crews.DeleteObject(get);
            }
        }

        /// <summary>
        /// Save Crew object
        /// </summary>
        /// <param name="crewDto"></param>
        /// <returns></returns>
        private void SaveCrew_Sub(CrewDto crewDto)
        {
            var get = GetCrewModelById(crewDto.CrewId);

            if (get != null && get.IsTemp == crewDto.IsTemp)
            {
                // Update
                get.CrewId = crewDto.CrewId;
                get.DocumentId = crewDto.DocumentId;
                get.FamilyName = crewDto.FamilyName;
                get.GivenName = crewDto.GivenName;
                get.Rank = crewDto.Rank;
                get.StateId = crewDto.StateId;
                get.BirthDate = crewDto.BirthDate;
                get.BirthPlace = crewDto.BirthPlace;
                get.PassportType = crewDto.PassportType;
                get.PassportNumber = crewDto.PassportNumber;
                get.PassportValidDate = crewDto.PassportValidDate;
                get.ItemStatus = crewDto.ItemStatus;
                get.CreaterId = crewDto.CreaterId;
                get.ModifyId = crewDto.ModifyId;
                get.IsTemp = crewDto.IsTemp;
            }
            else
            {
                // Insert
                if (crewDto.IsTemp)
                    crewDto.CrewId = Guid.NewGuid();
                get = ConvertCrewDtoToModel(crewDto);
                eManifestModel.Crews.AddObject(get);
            }
        }

        /// <summary>
        /// Save Crew object
        /// </summary>
        /// <param name="crewDto"></param>
        /// <returns></returns>
        private void SaveCrews_Sub(List<CrewDto> crewDtos, bool isTemp)
        {
            Guid documentId = crewDtos[0].DocumentId;

            var get = (from o in eManifestModel.Crews
                       where o.DocumentId == documentId && o.IsTemp == isTemp
                       select o).ToList();

            // Delete
            if (get != null)
            {
                foreach (var item in get)
                {
                    var search = (from o in crewDtos
                                  where o.CrewId == item.CrewId
                                  select o).FirstOrDefault();

                    if (search == null)
                    {
                        DeleteCrewById(item.CrewId);
                    }
                }
            }

            // Add and Update
            foreach (var item in crewDtos)
            {
                SaveCrew_Sub(item);
            }
        }

        /// <summary>
        /// Delete object by Id
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        public void DeleteCrewById(Guid id)
        {
            DeleteCrew_Sub(id);
            eManifestModel.SaveChanges();
        }

        /// <summary>
        /// Delete object by documentId
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        public ResponseDto DeleteCrewByDocumentId(Guid documentId, Guid userId)
        {

            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            eManifestModel.DeleteCrew(documentId, userId);

            //try
            //{
            //    bool isTemp = IsSubmitDocument(documentId);

            //    DeleteCrewByDocumentId_Sub(documentId, userId, isTemp);

            //    // Save change
            //    eManifestModel.SaveChanges();
            //}

            //catch (Exception ex)
            //{
            //    ret.IsSuccess = false;
            //    ret.ErroeMessage = ex.Message;
            //}

            return ret;
        }

        /// <summary>
        /// Save Crew object
        /// </summary>
        /// <param name="crewDto"></param>
        /// <returns></returns>
        public ResponseDto SaveCrew(List<CrewDto> crewDtos, bool isTemp = false)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            if (crewDtos.Count == 0) return ret;

            try
            {
                isTemp = IsSubmitDocument(crewDtos[0].DocumentId);
                foreach (var item in crewDtos)
                {
                    item.IsTemp = isTemp;
                }

                // Update document status
                if (isTemp)
                {
                    SetDocumentStatusUpdate(crewDtos[0].DocumentId, enumDocumentUpdate.Crew);
                }

                // Save
                SaveCrews_Sub(crewDtos, isTemp);

                // Save change
                eManifestModel.SaveChanges();
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Save Crew object
        /// </summary>
        /// <param name="crewDto"></param>
        /// <returns></returns>
        public ResponseDto SaveCrew(CrewDto crewDto, bool isTemp = false)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };


            try
            {
                isTemp = IsSubmitDocument(crewDto.DocumentId);

                crewDto.IsTemp = isTemp;

                // Update document status
                if (isTemp)
                {
                    SetDocumentStatusUpdate(crewDto.DocumentId, enumDocumentUpdate.Crew);
                }

                // Save
                SaveCrew_Sub(crewDto);

                // Save change
                eManifestModel.SaveChanges();
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }
        #endregion

        #region CrewEffectDeclaration

        /// <summary>
        /// Convert from model object to dto object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private CrewEffectDeclarationDto ConvertCrewEffectDeclarationModelToDto(CrewEffectDeclaration obj)
        {
            var ret = new CrewEffectDeclarationDto
            {
                CrewEffectDeclarationId = obj.CrewEffectDeclarationId,
                DocumentId = obj.DocumentId.Value,
                FullName = obj.FullName,
                Rank = obj.Rank,
                DutyPackage = obj.DutyPackage,
                ModifyId = obj.ModifyId,
                CreatedDate = obj.CreatedDate,
                CreaterId = obj.CreaterId,
                IsTemp = obj.IsTemp,
                UploadType = enumUploadType.Original
            };

            return ret;
        }

        /// <summary>
        /// Convert from dto object to model object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private CrewEffectDeclaration ConvertCrewEffectDeclarationDtoToModel(CrewEffectDeclarationDto obj)
        {
            var ret = new CrewEffectDeclaration
            {
                CrewEffectDeclarationId = obj.CrewEffectDeclarationId,
                DocumentId = obj.DocumentId,
                FullName = obj.FullName,
                Rank = obj.Rank,
                DutyPackage = obj.DutyPackage,
                ModifyId = obj.ModifyId,
                CreatedDate = obj.CreatedDate,
                CreaterId = obj.CreaterId,
                IsTemp = obj.IsTemp,
            };

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        private CrewEffectDeclaration GetCrewEffectDeclarationModelById(Guid id)
        {
            var ret = (from o in eManifestModel.CrewEffectDeclarations
                       where o.CrewEffectDeclarationId == id
                       select o).FirstOrDefault() as CrewEffectDeclaration;

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        public CrewEffectDeclarationDto GetCrewEffectDeclarationById(Guid id)
        {
            CrewEffectDeclarationDto ret = null;

            var get = GetCrewEffectDeclarationModelById(id);

            if (get != null)
            {
                ret = ConvertCrewEffectDeclarationModelToDto(get);
            }

            return ret;
        }

        /// <summary>
        /// Get list CrewEffectDeclarations by CrewEffectDeclaration name
        /// </summary>
        /// <returns></returns>
        public List<CrewEffectDeclarationDto> GetListCrewEffectDeclaration(Guid documentId, Guid userId)
        {
            var lstret = new List<CrewEffectDeclarationDto>();

            // Get from temp
            var get = (from o in eManifestModel.CrewEffectDeclarations
                       where o.DocumentId == documentId && o.CreaterId == userId && o.IsTemp == true
                       select o).ToList();

            if (get != null)
            {
                if (get.Count > 0)
                {
                    foreach (var item in get)
                    {
                        lstret.Add(ConvertCrewEffectDeclarationModelToDto(item));
                    }
                    return lstret;
                }
            }

            // Get from submited
            get = (from o in eManifestModel.CrewEffectDeclarations
                   where o.DocumentId == documentId && o.CreaterId == userId && o.IsTemp == false
                   select o).ToList();

            if (get != null)
            {
                if (get.Count > 0)
                {
                    foreach (var item in get)
                    {
                        lstret.Add(ConvertCrewEffectDeclarationModelToDto(item));
                    }
                }
            }

            return lstret;
        }

        /// <summary>
        /// Delete object by document Id
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        private void DeleteCrewEffectDeclarationByDocumentId_Sub(Guid documentId)
        {
            var get = (from o in eManifestModel.CrewEffectDeclarations
                       where o.DocumentId == documentId
                       select o).ToList();

            if (get != null)
            {
                foreach (var item in get)
                {
                    DeleteCrewEffectDeclaration_Sub(item.CrewEffectDeclarationId);
                }
            }
        }

        /// <summary>
        /// Delete object by document Id
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        private void DeleteCrewEffectDeclaration_Sub(Guid id)
        {
            var get = GetCrewEffectDeclarationModelById(id);

            if (get != null)
            {
                eManifestModel.CrewEffectDeclarations.DeleteObject(get);
            }
        }

        /// <summary>
        /// Delete object by documentId and isTemp
        /// </summary>
        /// <param name="documentId"></param>
        /// <param name="isTemp"></param>
        /// <returns></returns>
        private void DeleteCrewEffectDeclarationByDocumentId_Sub(Guid documentId, Guid createrId, bool isTemp)
        {
            var get = (from o in eManifestModel.CrewEffectDeclarations
                       where o.DocumentId == documentId && o.IsTemp == isTemp && (createrId == Guid.Empty ? true : o.CreaterId == createrId)
                       select o);

            if (get == null) return;

            List<Guid> lstGuidId = new List<Guid>();
            foreach (var item in get)
            {
                lstGuidId.Add(item.CrewEffectDeclarationId);
            }

            foreach (var id in lstGuidId)
            {
                DeleteCrewEffectDeclarationById(id);
            }
        }

        /// <summary>
        /// Save CrewEffectDeclaration object
        /// </summary>
        /// <param name="crewEffectDeclarationDto"></param>
        /// <returns></returns>
        private void SaveCrewEffectDeclaration_Sub(CrewEffectDeclarationDto crewEffectDeclarationDto)
        {
            var get = GetCrewEffectDeclarationModelById(crewEffectDeclarationDto.CrewEffectDeclarationId);

            if (get != null)
            {
                // Update
                get.CrewEffectDeclarationId = crewEffectDeclarationDto.CrewEffectDeclarationId;
                get.DocumentId = crewEffectDeclarationDto.DocumentId;
                get.FullName = crewEffectDeclarationDto.FullName;
                get.Rank = crewEffectDeclarationDto.Rank;
                get.DutyPackage = crewEffectDeclarationDto.DutyPackage;
                get.ModifyId = crewEffectDeclarationDto.ModifyId;
                get.CreaterId = crewEffectDeclarationDto.CreaterId;
                get.IsTemp = crewEffectDeclarationDto.IsTemp;
            }
            else
            {
                // Insert
                get = ConvertCrewEffectDeclarationDtoToModel(crewEffectDeclarationDto);
                eManifestModel.CrewEffectDeclarations.AddObject(get);
            }
        }

        /// <summary>
        /// Save CrewEffectDeclaration object
        /// </summary>
        /// <param name="CrewEffectDeclarationDto"></param>
        /// <returns></returns>
        private void SaveCrewEffectDeclarations_Sub(List<CrewEffectDeclarationDto> CrewEffectDeclarationDtos, bool isTemp)
        {
            Guid documentId = CrewEffectDeclarationDtos[0].DocumentId;

            var get = (from o in eManifestModel.CrewEffectDeclarations
                       where o.DocumentId == documentId && o.IsTemp == isTemp
                       select o).ToList();

            // Delete
            if (get != null)
            {
                foreach (var item in get)
                {
                    var search = (from o in CrewEffectDeclarationDtos
                                  where o.CrewEffectDeclarationId == item.CrewEffectDeclarationId
                                  select o).FirstOrDefault();

                    if (search == null)
                    {
                        DeleteCrewEffectDeclarationById(item.CrewEffectDeclarationId);
                    }
                }
            }

            // Add and Update
            foreach (var item in CrewEffectDeclarationDtos)
            {
                SaveCrewEffectDeclaration_Sub(item);
            }
        }

        /// <summary>
        /// Delete object by Id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public void DeleteCrewEffectDeclarationById(Guid id)
        {
            var get = GetCrewEffectDeclarationModelById(id);

            if (get != null)
            {
                eManifestModel.CrewEffectDeclarations.DeleteObject(get);
            }
        }

        /// <summary>
        /// Delete object by documentId
        /// </summary>
        /// <param name="documentId"></param>
        /// <param name="isTemp"></param>
        /// <returns></returns>
        private ResponseDto DeleteCrewEffectDeclarationByDocumentId(Guid documentId, bool isTemp = false)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                DeleteCrewEffectDeclarationByDocumentId_Sub(documentId, Guid.Empty, isTemp);

                // Save change
                eManifestModel.SaveChanges();
            }

            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Delete object by documentId and userId
        /// </summary>
        /// <param name="documentId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public ResponseDto DeleteCrewEffectDeclarationByDocumentId(Guid documentId, Guid userId)
        {

            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            eManifestModel.DeleteCrewEffectDeclaration(documentId, userId);

            return ret;
        }
        /// <summary>
        /// Save CrewEffectDeclaration object
        /// </summary>
        /// <param name="CrewEffectDeclarationDto"></param>
        /// <returns></returns>
        public ResponseDto SaveCrewEffectDeclaration(List<CrewEffectDeclarationDto> crewEffectDeclarationDtos, bool isTemp = false)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            if (crewEffectDeclarationDtos.Count == 0) return ret;

            try
            {
                isTemp = IsSubmitDocument(crewEffectDeclarationDtos[0].DocumentId);
                foreach (var item in crewEffectDeclarationDtos)
                {
                    item.IsTemp = isTemp;
                }

                // Update document status
                if (isTemp)
                {
                    SetDocumentStatusUpdate(crewEffectDeclarationDtos[0].DocumentId, enumDocumentUpdate.CrewEffectDeclaration);
                }

                // Save
                SaveCrewEffectDeclarations_Sub(crewEffectDeclarationDtos, isTemp);

                // Save change
                eManifestModel.SaveChanges();
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }



        #endregion

        #region Passenger

        /// <summary>
        /// Convert from model object to dto object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private PassengerDto ConvertPassengerModelToDto(Passenger obj)
        {
            var ret = new PassengerDto
            {
                PassengerId = obj.PassengerId,
                DocumentId = obj.DocumentId,
                FamilyName = obj.FamilyName,
                GivenName = obj.GivenName,
                StateId = obj.StateId,
                BirthDate = obj.BirthDate,
                BirthPlace = obj.BirthPlace,
                PassportType = obj.PassportType.Trim(),
                PassportNumber = obj.PassportNumber,
                PassportValidDate = obj.PassportValidDate,
                PortIdOfEmbarkation = obj.PortIdOfEmbarkation,
                PortIdOfDisembarkation = obj.PortOfDisembarkation,
                PortNameOfEmbarkation = obj.PortNameOfEmbarkation,
                PortNameOfDisembarkation = obj.PortNameOfDisembarkation,
                IsTransit = obj.IsTransit,
                ItemStatus = obj.ItemStatus,
                CreatedDate = obj.CreatedDate,
                CreaterId = obj.CreaterId,
                PortId = obj.PortId,
                ModifyId = obj.ModifyId,
                IsTemp = obj.IsTemp,
                UploadType = enumUploadType.Original
            };

            //// Passport type
            //if (obj.PassportType1 != null)
            //{
            //    ret.PassportTypeDto = ConvertPassportTypeModelToDto(obj.PassportType1);
            //}
            //// State
            //if (obj.State != null)
            //{
            //    ret.State = ConvertStateModelToDto(obj.State);
            //}
            //// Port
            //if (obj.Port1 != null)
            //{
            //    ret.Port = ConvertPortModelToDto(obj.Port1);
            //}

            return ret;
        }

        /// <summary>
        /// Convert from dto object to model object
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        private Passenger ConvertPassengerDtoToModel(PassengerDto obj)
        {
            var ret = new Passenger
            {
                PassengerId = obj.PassengerId,
                DocumentId = obj.DocumentId,
                FamilyName = obj.FamilyName,
                GivenName = obj.GivenName,
                StateId = obj.StateId,
                BirthDate = obj.BirthDate,
                BirthPlace = obj.BirthPlace,
                PassportType = obj.PassportType,
                PassportNumber = obj.PassportNumber,
                PassportValidDate = obj.PassportValidDate,
                PortIdOfEmbarkation = obj.PortIdOfEmbarkation,
                PortOfDisembarkation = obj.PortIdOfDisembarkation,
                PortNameOfEmbarkation = obj.PortNameOfEmbarkation,
                PortNameOfDisembarkation = obj.PortNameOfDisembarkation,
                IsTransit = obj.IsTransit,
                ItemStatus = obj.ItemStatus,
                CreatedDate = obj.CreatedDate,
                CreaterId = obj.CreaterId,
                PortId = obj.PortId,
                ModifyId = obj.ModifyId,
                IsTemp = obj.IsTemp,
            };

            return ret;
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        private Passenger GetPassengerModelById(Guid id)
        {
            var ret = (from o in eManifestModel.Passengers
                       where o.PassengerId == id
                       select o).FirstOrDefault() as Passenger;

            return ret;
        }

        /// <summary>
        /// Delete object by documentId
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        private void DeletePassengerByDocumentId_Sub(Guid documentId, Guid createrId, bool isTemp)
        {
            var get = (from o in eManifestModel.Passengers
                       where o.DocumentId == documentId && o.IsTemp == isTemp && (createrId == Guid.Empty ? true : o.CreaterId == createrId)
                       select o);

            if (get == null) return;

            List<Guid> lstGuidId = new List<Guid>();
            foreach (var item in get)
            {
                lstGuidId.Add(item.PassengerId);
            }

            foreach (var id in lstGuidId)
            {
                DeletePassengerById(id);
            }
        }

        /// <summary>
        /// Get object by id
        /// </summary>
        /// <returns></returns>
        public PassengerDto GetPassengerById(Guid id)
        {
            PassengerDto ret = null;

            var get = GetPassengerModelById(id);

            if (get != null)
            {
                ret = ConvertPassengerModelToDto(get);
            }

            return ret;
        }

        /// <summary>
        /// Delete object by document Id
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        private void DeletePassengerByDocumentId_Sub(Guid documentId)
        {
            var get = (from o in eManifestModel.Passengers
                       where o.DocumentId == documentId
                       select o).ToList();

            if (get != null)
            {
                foreach (var item in get)
                {
                    DeletePassenger_Sub(item.PassengerId);
                }
            }
        }

        /// <summary>
        /// Delete object by document Id
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        private void DeletePassenger_Sub(Guid id)
        {
            var get = GetPassengerModelById(id);

            if (get != null)
            {
                eManifestModel.Passengers.DeleteObject(get);
            }
        }

        /// <summary>
        /// Get list Passengers by Passenger name
        /// </summary>
        /// <returns></returns>
        public List<PassengerDto> GetListPassenger(Guid documentId, Guid userId)
        {
            var lstret = new List<PassengerDto>();

            // Get from temp
            var get = (from o in eManifestModel.Passengers
                       where o.DocumentId == documentId && o.CreaterId == userId && o.IsTemp == true
                       select o).ToList();

            if (get != null)
            {
                if (get.Count > 0)
                {
                    foreach (var item in get)
                    {
                        lstret.Add(ConvertPassengerModelToDto(item));
                    }
                    return lstret;
                }
            }

            // Get from submited
            get = (from o in eManifestModel.Passengers
                   where o.DocumentId == documentId && o.CreaterId == userId && o.IsTemp == false
                   select o).ToList();

            if (get != null)
            {
                if (get.Count > 0)
                {
                    foreach (var item in get)
                    {
                        lstret.Add(ConvertPassengerModelToDto(item));
                    }
                }
            }

            return lstret;
        }

        /// <summary>
        /// Save Passenger object
        /// </summary>
        /// <param name="passengerDto"></param>
        /// <returns></returns>
        private void SavePassenger_Sub(PassengerDto passengerDto)
        {
            var get = GetPassengerModelById(passengerDto.PassengerId);

            if (get != null)
            {
                // Update
                get.PassengerId = passengerDto.PassengerId;
                get.DocumentId = passengerDto.DocumentId;
                get.FamilyName = passengerDto.FamilyName;
                get.GivenName = passengerDto.GivenName;
                get.StateId = passengerDto.StateId;
                get.BirthDate = passengerDto.BirthDate;
                get.BirthPlace = passengerDto.BirthPlace;
                get.PassportType = passengerDto.PassportType;
                get.PassportNumber = passengerDto.PassportNumber;
                get.PassportValidDate = passengerDto.PassportValidDate;
                get.ItemStatus = passengerDto.ItemStatus;
                get.CreaterId = passengerDto.CreaterId;
                get.PortId = passengerDto.PortId;
                get.ModifyId = passengerDto.ModifyId;
                get.IsTemp = passengerDto.IsTemp;
            }
            else
            {
                // Insert
                get = ConvertPassengerDtoToModel(passengerDto);
                eManifestModel.Passengers.AddObject(get);
            }
        }

        /// <summary>
        /// Save Passenger object
        /// </summary>
        /// <param name="PassengerDto"></param>
        /// <returns></returns>
        private void SavePassengers_Sub(List<PassengerDto> passengerDtos, bool isTemp)
        {
            Guid documentId = passengerDtos[0].DocumentId;
            var get = (from o in eManifestModel.Passengers
                       where o.DocumentId == documentId && o.IsTemp == isTemp
                       select o).ToList();

            // Delete
            if (get != null)
            {
                foreach (var item in get)
                {
                    var search = (from o in passengerDtos
                                  where o.PassengerId == item.PassengerId
                                  select o).FirstOrDefault();

                    if (search == null)
                    {
                        DeletePassengerById(item.PassengerId);
                    }
                }
            }

            // Add and Update
            foreach (var item in passengerDtos)
            {
                SavePassenger_Sub(item);
            }
        }



        /// <summary>
        /// Delete object by Id
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        public ResponseDto DeletePassengerById(Guid id)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };
            try
            {
            var get = GetPassengerModelById(id);

            if (get != null)
            {
                eManifestModel.Passengers.DeleteObject(get);
            }
            eManifestModel.SaveChanges();
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }
            return ret;
        }
        // Save 1 record
        

        /// <summary>
        /// Delete object by documentId
        /// </summary>
        /// <param name="shipId"></param>
        /// <returns></returns>
        private ResponseDto DeletePassengerByDocumentId(Guid documentId, bool isTemp = false)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                DeletePassengerByDocumentId_Sub(documentId, Guid.Empty, isTemp);

                // Save change
                eManifestModel.SaveChanges();
            }

            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        /// <summary>
        /// Delete object by documentId
        /// </summary>
        /// <param name="documentId"></param>
        /// <returns></returns>
        public ResponseDto DeletePassengerByDocumentId(Guid documentId, Guid userId)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            eManifestModel.DeletePassenger(documentId, userId);
            return ret;
        }

          
            /// <summary>
            /// Save Passenger object
            /// </summary>
            /// <param name="PassengerDto"></param>
            /// <returns></returns>
        
        public ResponseDto SavePassenger(List<PassengerDto> passengerDtos, bool isTemp = false)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            if (passengerDtos.Count == 0) return ret;

            try
            {
                isTemp = IsSubmitDocument(passengerDtos[0].DocumentId);
                foreach (var item in passengerDtos)
                {
                    item.IsTemp = isTemp;
                }

                // Update document status
                if (isTemp)
                {
                    SetDocumentStatusUpdate(passengerDtos[0].DocumentId, enumDocumentUpdate.Passenger);
                }

                // Save
                SavePassengers_Sub(passengerDtos, isTemp);

                // Save change
                eManifestModel.SaveChanges();

            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }

        #endregion

        #region Guarantee Users
        public List<Guid> GetListUserIdByCreaterId(Guid createrId)
        {
            List<Guid> lst = new List<Guid>();
            var q = (from o in eManifestModel.UsersGuaranteeUsers
                     where o.CreateId == createrId
                     select o);
            foreach (var o in q)
            {
                lst.Add(o.UserId);
            }

            return lst;
        }

        public ResponseDto SaveGuaranteeUser(UsersGuaranteeUserDto guaUser)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {
                var get = GetUsersGuaranteeUserModelByIds(guaUser.CreaterId, guaUser.UserId);
                if (get == null)
                {
                    // Insert
                    get = ConvertUsersGuaranteeUserDtoToModel(guaUser);

                    eManifestModel.UsersGuaranteeUsers.AddObject(get);
                    // Save change
                    eManifestModel.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }
            return ret;
        }

        private UsersGuaranteeUser GetUsersGuaranteeUserModelByIds(Guid createrId, Guid userId)
        {
            var ret = (from o in eManifestModel.UsersGuaranteeUsers
                       where o.CreateId == createrId && o.UserId == userId
                       select o).FirstOrDefault() as UsersGuaranteeUser;

            return ret;
        }
        private UsersGuaranteeUser ConvertUsersGuaranteeUserDtoToModel(UsersGuaranteeUserDto user)
        {
            var ret = new UsersGuaranteeUser
            {
                CreateId = user.CreaterId,
                UserId = user.UserId,
                CreatedDate = DateTime.Now,
                Description = user.Description,
            };

            return ret;
        }
        #endregion

        #region Notice
        public ResponseDto SaveNoticeShipTo(NoticeShipToDto notice)
        {
            var ret = new ResponseDto { IsSuccess = true, ErroeMessage = string.Empty };

            try
            {

                //Update Document.ArrivalDate
                Document document = eManifestModel.Documents.FirstOrDefault(c => c.DocumentId == notice.DocumentId && c.OwnerId == notice.CreaterId);
                if (document != null)
                {
                    document.ArrivalDate = notice.Time;
                    document.ValidDays = 30;

                    NoticeShip oNotice = eManifestModel.NoticeShips.FirstOrDefault(c => c.DocumentId == notice.DocumentId && c.CreaterId == notice.CreaterId);
                    if (oNotice == null)
                        oNotice = new NoticeShip();
                    oNotice.CreatedDate = notice.Time;
                    oNotice.DocumentId = notice.DocumentId;
                    oNotice.Description = notice.Description;
                    oNotice.CreaterId = notice.CreaterId;

                    eManifestModel.ObjectStateManager.ChangeObjectState(document, EntityState.Modified);
                    document.NoticeShip = oNotice;

                    // Insert
                    eManifestModel.NoticeShips.AddObject(oNotice);

                    // Save change
                    // Save documenthistory
                    
                    var get = GetDocumentModelById(oNotice.DocumentId);
                    SaveDocumentHistory(get, oNotice.CreaterId, string.Empty, " Gửi thông báo tàu đến rời");
                    eManifestModel.SaveChanges();
                }

            }
            catch (Exception ex)
            {
                ret.IsSuccess = false;
                ret.ErroeMessage = ex.Message;
            }

            return ret;
        }
        #endregion




    }
}
